/**
 * 单个产品API路由
 * 作者: 阿瑞
 * 功能: 提供单个产品的查询、更新和删除接口
 * 版本: 2.0.0
 */

import { NextRequest, NextResponse } from 'next/server';
import { RequestWithDB, connectTeamDB } from '@/lib/db';
import { RowDataPacket } from 'mysql2';

/**
 * 为请求添加团队信息
 * @param req 原始请求对象
 * @param teamCode 团队代码
 * @returns 包含团队信息的新请求对象
 */
const addTeamInfoToRequest = (req: NextRequest, teamCode: string): NextRequest => {
  // 创建新的请求对象
  const teamReq = new NextRequest(req.url, {
    method: req.method,
    headers: new Headers(req.headers),
    body: req.body,
    cache: req.cache,
    credentials: req.credentials,
    integrity: req.integrity,
    keepalive: req.keepalive,
    mode: req.mode,
    redirect: req.redirect,
    referrer: req.referrer,
    referrerPolicy: req.referrerPolicy
  });
  
  // 添加团队ID信息
  teamReq.headers.set('x-team-id', teamCode);
  
  return teamReq;
};

/**
 * 从URL路径中提取参数
 * @param req 请求对象
 * @returns 提取的参数对象
 */
const extractParamsFromPath = (req: NextRequest): { teamCode: string; id: string } => {
  // 路径格式: /api/team/[teamCode]/products/[id]
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3，产品ID位于索引5
  return {
    teamCode: pathParts[3] || '',
    id: pathParts[5] || ''
  };
};

/**
 * 获取单个产品
 */
const getProduct = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  const teamCode = params?.teamCode as string;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的产品ID' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始查询团队[${teamCode}]产品, ID:${id}`);
    
    // 查询产品信息，包括关联的供应商、品牌、品类名称
    const [rows] = await req.db.query(
      `SELECT 
        p.id, p.supplier_id as supplierId, p.brand_id as brandId, p.category_id as categoryId, 
        p.name, p.description, p.code, p.image, p.sku, p.aliases, p.level, p.cost, 
        p.price, p.stock, p.logistics_status as logisticsStatus, 
        p.logistics_details as logisticsDetails, p.tracking_number as trackingNumber,
        p.created_at as createdAt, p.updated_at as updatedAt,
        s.name as supplierName, b.name as brandName, c.name as categoryName
      FROM products p
      LEFT JOIN suppliers s ON p.supplier_id = s.id
      LEFT JOIN brands b ON p.brand_id = b.id
      LEFT JOIN categories c ON p.category_id = c.id
      WHERE p.id = ?`,
      [id]
    );
    
    if (!Array.isArray(rows) || rows.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应产品' },
        { status: 404 }
      );
    }
    
    // 处理产品数据
    const product: {
      id: number;
      aliases?: string | string[];
      cost?: string | Record<string, number>;
      [key: string]: string | number | boolean | null | string[] | Record<string, number> | undefined;
    } = rows[0] as RowDataPacket & {
      id: number;
      aliases?: string | string[];
      cost?: string | Record<string, number>;
      [key: string]: string | number | boolean | null | string[] | Record<string, number> | undefined;
    };
    
    // 处理JSON字段
    if (product.aliases && typeof product.aliases === 'string') {
      try {
        product.aliases = JSON.parse(product.aliases);
      } catch (error) {
        console.error('解析别名JSON失败:', error);
        product.aliases = [];
      }
    }
    
    if (product.cost && typeof product.cost === 'string') {
      try {
        product.cost = JSON.parse(product.cost);
      } catch (error) {
        console.error('解析成本JSON失败:', error);
        product.cost = {};
      }
    }
    
    console.log(`查询团队[${teamCode}]产品成功, ID:${id}`);
    
    return NextResponse.json({
      success: true,
      product
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]产品详情失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取产品详情失败' },
      { status: 500 }
    );
  }
};

/**
 * 更新产品
 */
const updateProduct = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  const teamCode = params?.teamCode as string;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的产品ID' },
      { status: 400 }
    );
  }
  
  // 获取请求数据或使用预解析的数据
  const data = req.parsedBody || await req.json();
  
  // 验证是否有需要更新的字段
  if (Object.keys(data).length === 1 && data.id) {
    return NextResponse.json(
      { success: false, error: '缺少需要更新的字段' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始更新团队[${teamCode}]产品, ID:${id}`);
    
    // 使用数据库连接
    const connection = req.db;
    
    try {
      await connection.beginTransaction();
      
      // 检查产品是否存在
      const [existingProduct] = await connection.query(
        'SELECT id FROM products WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingProduct) || existingProduct.length === 0) {
        await connection.rollback();
        return NextResponse.json(
          { success: false, error: '未找到相应产品' },
          { status: 404 }
        );
      }
      
      // 处理JSON字段
      let aliasesJson = undefined;
      if (data.aliases !== undefined) {
        aliasesJson = data.aliases ? JSON.stringify(data.aliases) : null;
      }
      
      let costJson = undefined;
      if (data.cost !== undefined) {
        costJson = data.cost ? JSON.stringify(data.cost) : null;
      }
      
      // 构建更新SQL
      const updateFields = [];
      const updateParams = [];
      
      // 映射字段名
      const fieldMappings: Record<string, string> = {
        supplierId: 'supplier_id',
        brandId: 'brand_id',
        categoryId: 'category_id',
        logisticsStatus: 'logistics_status',
        logisticsDetails: 'logistics_details',
        trackingNumber: 'tracking_number',
      };
      
      // 特殊处理的字段
      const specialFields = ['aliases', 'cost', 'id'];
      
      // 添加常规字段
      for (const [key, value] of Object.entries(data)) {
        if (key === 'id' || specialFields.includes(key)) continue;
        
        const dbField = fieldMappings[key] || key;
        updateFields.push(`${dbField} = ?`);
        updateParams.push(value === null ? null : value);
      }
      
      // 添加JSON字段
      if (aliasesJson !== undefined) {
        updateFields.push('aliases = ?');
        updateParams.push(aliasesJson);
      }
      
      if (costJson !== undefined) {
        updateFields.push('cost = ?');
        updateParams.push(costJson);
      }
      
      // 添加更新时间
      updateFields.push('updated_at = NOW()');
      
      // 如果没有需要更新的字段，返回错误
      if (updateFields.length === 1) {
        await connection.rollback();
        return NextResponse.json(
          { success: false, error: '缺少需要更新的字段' },
          { status: 400 }
        );
      }
      
      // 添加ID作为WHERE条件参数
      updateParams.push(id);
      
      const updateSql = `
        UPDATE products 
        SET ${updateFields.join(', ')} 
        WHERE id = ?
      `;
      
      await connection.query(updateSql, updateParams);
      
      // 查询更新后的产品信息，包括关联的供应商、品牌、品类名称
      const [updatedProductRows] = await connection.query(
        `SELECT 
          p.id, p.supplier_id as supplierId, p.brand_id as brandId, p.category_id as categoryId, 
          p.name, p.description, p.code, p.image, p.sku, p.aliases, p.level, p.cost, 
          p.price, p.stock, p.logistics_status as logisticsStatus, 
          p.logistics_details as logisticsDetails, p.tracking_number as trackingNumber,
          p.created_at as createdAt, p.updated_at as updatedAt,
          s.name as supplierName, b.name as brandName, c.name as categoryName
        FROM products p
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        LEFT JOIN brands b ON p.brand_id = b.id
        LEFT JOIN categories c ON p.category_id = c.id
        WHERE p.id = ?`,
        [id]
      );
      
      // 处理产品数据
      let updatedProduct = null;
      if (Array.isArray(updatedProductRows) && updatedProductRows.length > 0) {
        updatedProduct = updatedProductRows[0] as RowDataPacket & {
          id: number;
          aliases?: string | string[];
          cost?: string | Record<string, number>;
          [key: string]: string | number | boolean | null | string[] | Record<string, number> | undefined;
        };
        
        // 处理JSON字段
        if (updatedProduct.aliases && typeof updatedProduct.aliases === 'string') {
          try {
            updatedProduct.aliases = JSON.parse(updatedProduct.aliases);
          } catch (error) {
            console.error('解析别名JSON失败:', error);
            updatedProduct.aliases = [];
          }
        }
        
        if (updatedProduct.cost && typeof updatedProduct.cost === 'string') {
          try {
            updatedProduct.cost = JSON.parse(updatedProduct.cost);
          } catch (error) {
            console.error('解析成本JSON失败:', error);
            updatedProduct.cost = {};
          }
        }
      }
      
      // 提交事务
      await connection.commit();
      
      console.log(`更新团队[${teamCode}]产品成功, ID:${id}`);
      
      return NextResponse.json({
        success: true,
        message: '产品更新成功',
        product: updatedProduct
      });
    } catch (error) {
      // 发生错误时回滚事务
      await connection.rollback();
      throw error;
    }
  } catch (error) {
    console.error(`更新团队[${teamCode}]产品失败:`, error);
    return NextResponse.json(
      { success: false, error: '更新产品失败' },
      { status: 500 }
    );
  }
};

/**
 * 删除产品
 */
const deleteProduct = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  const teamCode = params?.teamCode as string;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的产品ID' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始删除团队[${teamCode}]产品, ID:${id}`);
    
    // 检查产品是否存在
    const [existingProduct] = await req.db.query(
      'SELECT id FROM products WHERE id = ?',
      [id]
    );
    
    if (!Array.isArray(existingProduct) || existingProduct.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应产品' },
        { status: 404 }
      );
    }
    
    // 直接删除产品记录
    await req.db.query('DELETE FROM products WHERE id = ?', [id]);
    
    console.log(`删除团队[${teamCode}]产品成功, ID:${id}`);
    
    return NextResponse.json({
      success: true,
      message: '产品删除成功'
    });
  } catch (error) {
    console.error(`删除团队[${teamCode}]产品失败:`, error);
    return NextResponse.json(
      { success: false, error: '删除产品失败' },
      { status: 500 }
    );
  }
};

// 导出处理函数
export async function GET(req: NextRequest) {
  try {
    // 从URL路径中提取参数
    const { teamCode, id } = extractParamsFromPath(req);
    
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return connectTeamDB(getProduct)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理产品详情请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
}

export async function PUT(req: NextRequest) {
  try {
    // 从URL路径中提取参数
    const { teamCode, id } = extractParamsFromPath(req);
    
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    // 克隆请求，确保body只被读取一次
    const clonedReq = req.clone();
    
    // 预先读取请求体
    let body;
    try {
      body = await clonedReq.json();
    } catch {
      // 如果无法解析JSON，继续处理
    }
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 传递body数据到teamReq的headers中，避免重复读取body
    if (body) {
      teamReq.headers.set('x-request-body', JSON.stringify(body));
    }
    
    // 使用新版的connectTeamDB中间件处理请求
    return connectTeamDB(updateProduct)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理产品更新请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(req: NextRequest) {
  try {
    // 从URL路径中提取参数
    const { teamCode, id } = extractParamsFromPath(req);
    
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return connectTeamDB(deleteProduct)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理产品删除请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 