/**
 * 简化的养殖场控制器
 * @file farmController-simple.js
 * @description 处理养殖场相关的请求，不包含关联查询
 */

const { Farm } = require('../models');
const { createSuccessResponse, createErrorResponse, createPaginatedResponse, SUCCESS_MESSAGES, ERROR_CODES } = require('../utils/apiResponse');

/**
 * 获取所有养殖场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAllFarms = async (req, res) => {
  try {
    console.log('🔄 开始获取养殖场列表...');
    
    const farms = await Farm.findAll({
      order: [['created_at', 'DESC']]
    });
    
    console.log(`✅ 成功获取 ${farms.length} 个养殖场`);
    
    res.status(200).json(createSuccessResponse(farms, SUCCESS_MESSAGES.DATA_RETRIEVED));
  } catch (error) {
    console.error('❌ 获取养殖场列表失败:', error);
    res.status(500).json(createErrorResponse(
      '获取养殖场列表失败: ' + error.message,
      ERROR_CODES.DATABASE_ERROR
    ));
  }
};

/**
 * 根据养殖场名称搜索养殖场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.searchFarmsByName = async (req, res) => {
  const searchStartTime = Date.now();
  const requestId = Math.random().toString(36).substr(2, 9);
  
  try {
    const { name } = req.query;
    const userAgent = req.get('User-Agent') || 'Unknown';
    const clientIP = req.ip || req.connection.remoteAddress || 'Unknown';
    
    console.log(`🔍 [后端搜索监听] 搜索请求开始:`, {
      requestId: requestId,
      keyword: name,
      timestamp: new Date().toISOString(),
      clientIP: clientIP,
      userAgent: userAgent,
      queryParams: req.query,
      headers: {
        'content-type': req.get('Content-Type'),
        'accept': req.get('Accept'),
        'referer': req.get('Referer')
      }
    });
    
    if (!name || name.trim() === '') {
      console.log(`❌ [后端搜索监听] 搜索关键词为空:`, {
        requestId: requestId,
        keyword: name
      });
      
      return res.status(400).json({
        success: false,
        message: '请提供搜索关键词'
      });
    }
    
    console.log(`🔄 [后端搜索监听] 开始数据库查询:`, {
      requestId: requestId,
      searchKeyword: name,
      searchPattern: `%${name}%`
    });
    
    const queryStartTime = Date.now();
    
    const farms = await Farm.findAll({
      where: {
        name: {
          [require('sequelize').Op.like]: `%${name}%`
        }
      },
      order: [['created_at', 'DESC']]
    });
    
    const queryTime = Date.now() - queryStartTime;
    const totalTime = Date.now() - searchStartTime;
    
    console.log(`📊 [后端搜索监听] 数据库查询完成:`, {
      requestId: requestId,
      queryTime: queryTime + 'ms',
      totalTime: totalTime + 'ms',
      resultCount: farms.length,
      searchKeyword: name
    });
    
    // 记录搜索结果详情
    if (farms.length > 0) {
      console.log(`📋 [后端搜索监听] 搜索结果详情:`, {
        requestId: requestId,
        results: farms.map(farm => ({
          id: farm.id,
          name: farm.name,
          type: farm.type,
          status: farm.status,
          address: farm.address
        }))
      });
    }
    
    console.log(`✅ [后端搜索监听] 搜索成功:`, {
      requestId: requestId,
      keyword: name,
      resultCount: farms.length,
      responseTime: totalTime + 'ms'
    });
    
    res.status(200).json({
      success: true,
      data: farms,
      meta: {
        requestId: requestId,
        searchKeyword: name,
        resultCount: farms.length,
        queryTime: queryTime,
        totalTime: totalTime,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    const errorTime = Date.now() - searchStartTime;
    
    console.error(`❌ [后端搜索监听] 搜索失败:`, {
      requestId: requestId,
      error: error.message,
      stack: error.stack,
      errorTime: errorTime + 'ms',
      keyword: req.query.name
    });
    
    res.status(500).json({
      success: false,
      message: '搜索养殖场失败',
      error: error.message,
      meta: {
        requestId: requestId,
        errorTime: errorTime,
        timestamp: new Date().toISOString()
      }
    });
  }
};

/**
 * 根据ID获取养殖场详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getFarmById = async (req, res) => {
  try {
    const { id } = req.params;
    
    if (!id || isNaN(parseInt(id))) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的养殖场ID'
      });
    }
    
    console.log(`🔄 开始获取养殖场详情: ID=${id}`);
    
    const farm = await Farm.findByPk(id);
    
    if (!farm) {
      return res.status(404).json({
        success: false,
        message: '养殖场不存在'
      });
    }
    
    console.log(`✅ 成功获取养殖场详情: ${farm.name}`);
    
    res.status(200).json({
      success: true,
      data: farm
    });
  } catch (error) {
    console.error('❌ 获取养殖场详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取养殖场详情失败',
      error: error.message
    });
  }
};

/**
 * 创建新养殖场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.createFarm = async (req, res) => {
  try {
    const { name, type, location, address, contact, phone, status } = req.body;
    
    // 验证必填字段
    if (!name || !type) {
      return res.status(400).json({
        success: false,
        message: '养殖场名称和类型为必填项'
      });
    }
    
    console.log(`🔄 开始创建养殖场: ${name}`);
    
    const farm = await Farm.create({
      name,
      type,
      location: location || {},
      address,
      contact,
      phone,
      status: status || 'active'
    });
    
    console.log(`✅ 成功创建养殖场: ID=${farm.id}, 名称=${farm.name}`);
    
    res.status(201).json({
      success: true,
      data: farm,
      message: '养殖场创建成功'
    });
  } catch (error) {
    console.error('❌ 创建养殖场失败:', error);
    res.status(500).json({
      success: false,
      message: '创建养殖场失败',
      error: error.message
    });
  }
};

/**
 * 更新养殖场信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateFarm = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, type, location, address, contact, phone, status } = req.body;
    
    if (!id || isNaN(parseInt(id))) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的养殖场ID'
      });
    }
    
    console.log(`🔄 开始更新养殖场: ID=${id}`);
    
    const farm = await Farm.findByPk(id);
    
    if (!farm) {
      return res.status(404).json({
        success: false,
        message: '养殖场不存在'
      });
    }
    
    // 更新字段
    if (name) farm.name = name;
    if (type) farm.type = type;
    if (location) farm.location = location;
    if (address !== undefined) farm.address = address;
    if (contact !== undefined) farm.contact = contact;
    if (phone !== undefined) farm.phone = phone;
    if (status) farm.status = status;
    
    await farm.save();
    
    console.log(`✅ 成功更新养殖场: ID=${farm.id}, 名称=${farm.name}`);
    
    res.status(200).json({
      success: true,
      data: farm,
      message: '养殖场更新成功'
    });
  } catch (error) {
    console.error('❌ 更新养殖场失败:', error);
    res.status(500).json({
      success: false,
      message: '更新养殖场失败',
      error: error.message
    });
  }
};

/**
 * 删除养殖场
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.deleteFarm = async (req, res) => {
  try {
    const { id } = req.params;
    
    if (!id || isNaN(parseInt(id))) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的养殖场ID'
      });
    }
    
    console.log(`🔄 开始删除养殖场: ID=${id}`);
    
    const farm = await Farm.findByPk(id);
    
    if (!farm) {
      return res.status(404).json({
        success: false,
        message: '养殖场不存在'
      });
    }
    
    await farm.destroy();
    
    console.log(`✅ 成功删除养殖场: ID=${id}, 名称=${farm.name}`);
    
    res.status(200).json({
      success: true,
      message: '养殖场删除成功'
    });
  } catch (error) {
    console.error('❌ 删除养殖场失败:', error);
    res.status(500).json({
      success: false,
      message: '删除养殖场失败',
      error: error.message
    });
  }
};
