/**
 * 产品API路由
 * 作者: 阿瑞
 * 功能: 提供产品数据的查询和创建接口
 * 版本: 2.0.0
 */

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

// 产品数据类型接口
interface ProductRow extends RowDataPacket {
  id: number;
  supplierId?: number;
  supplierName?: string;
  brandId?: number;
  brandName?: string;
  categoryId?: number;
  categoryName?: string;
  name: string;
  description?: string;
  code?: string;
  image?: string;
  sku?: string;
  aliases?: string | string[];
  level?: string;
  cost?: string | Record<string, number>;
  price: number;
  stock: number;
  logisticsStatus?: string;
  logisticsDetails?: string;
  trackingNumber?: string;
  createdAt: Date;
  updatedAt: Date;
  supplier?: { id: number; name: string };
  brand?: { id: number; name: string };
  category?: { id: number; name: string };
}

/**
 * 为请求添加团队信息
 * @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;
};

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

/**
 * GET 获取产品列表
 */
const getProducts = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const teamCode = params?.teamCode as string;
  
  // 获取查询参数
  const url = new URL(req.url);
  const page = parseInt(url.searchParams.get('page') || '1');
  const pageSize = parseInt(url.searchParams.get('pageSize') || '10');
  const keyword = url.searchParams.get('keyword') || '';
  const supplierId = url.searchParams.get('supplierId') || '';
  const brandId = url.searchParams.get('brandId') || '';
  const categoryId = url.searchParams.get('categoryId') || '';
  
  // 计算偏移量
  const offset = (page - 1) * pageSize;
  
  try {
    console.log(`开始查询团队[${teamCode}]产品列表, 页码:${page}, 每页:${pageSize}`);
    
    // 构建查询条件
    const conditions = [];
    const queryParams = [];
    
    if (keyword) {
      conditions.push('(p.name LIKE ? OR p.code LIKE ? OR p.sku LIKE ? OR p.description LIKE ?)');
      queryParams.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`, `%${keyword}%`);
    }
    
    if (supplierId) {
      conditions.push('p.supplier_id = ?');
      queryParams.push(supplierId);
    }
    
    if (brandId) {
      conditions.push('p.brand_id = ?');
      queryParams.push(brandId);
    }
    
    if (categoryId) {
      conditions.push('p.category_id = ?');
      queryParams.push(categoryId);
    }
    
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    // 使用数据库连接
    const connection = req.db;
    
    // 查询总数
    const countSql = `
      SELECT COUNT(*) as total 
      FROM products p
      ${whereClause}
    `;
    const [totalRows] = await connection.query<RowDataPacket[]>(countSql, queryParams);
    
    const total = totalRows[0].total as number;
    
    // 查询分页数据
    const querySql = `
      SELECT 
        p.id, p.supplier_id as supplierId, s.name as supplierName,
        p.brand_id as brandId, b.name as brandName,
        p.category_id as categoryId, c.name as categoryName,
        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
      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
      ${whereClause}
      ORDER BY p.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    // 添加分页参数
    const paginatedParams = [...queryParams, pageSize, offset];
    
    const [rows] = await connection.query<ProductRow[]>(querySql, paginatedParams);
    
    // 处理查询结果
    let products = rows;
    
    // 处理别名和成本字段的JSON解析
    products = products.map(product => {
      // 处理别名字段
      if (product.aliases && typeof product.aliases === 'string') {
        try {
          product.aliases = JSON.parse(product.aliases) as string[];
        } catch (error) {
          console.error('解析别名JSON失败:', error);
          product.aliases = [] as string[];
        }
      }
      
      // 处理成本字段
      if (product.cost && typeof product.cost === 'string') {
        try {
          product.cost = JSON.parse(product.cost) as Record<string, number>;
        } catch (error) {
          console.error('解析成本JSON失败:', error);
          product.cost = {} as Record<string, number>;
        }
      }
      
      // 处理关联对象
      if (product.supplierId && product.supplierName) {
        product.supplier = {
          id: product.supplierId,
          name: product.supplierName
        };
      }
      
      if (product.brandId && product.brandName) {
        product.brand = {
          id: product.brandId,
          name: product.brandName
        };
      }
      
      if (product.categoryId && product.categoryName) {
        product.category = {
          id: product.categoryId,
          name: product.categoryName
        };
      }
      
      return product;
    });
    
    console.log(`查询团队[${teamCode}]产品列表成功, 总数:${total}`);
    
    return NextResponse.json({
      success: true,
      total,
      products
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]产品列表失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取产品列表失败' },
      { status: 500 }
    );
  }
};

/**
 * POST 创建产品
 */
const createProduct = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const teamCode = params?.teamCode as string;
  
  // 获取请求数据
  const data = await req.json();
  
  // 验证必填字段
  if (!data.name) {
    return NextResponse.json(
      { success: false, error: '产品名称为必填字段' },
      { status: 400 }
    );
  }
  
  if (data.price === undefined) {
    return NextResponse.json(
      { success: false, error: '产品价格为必填字段' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始创建团队[${teamCode}]产品, 名称:${data.name}`);
    
    // 使用数据库连接
    const connection = req.db;
    
    try {
      await connection.beginTransaction();
      
      // 处理JSON字段
      let aliasesJson = null;
      if (data.aliases && Array.isArray(data.aliases)) {
        aliasesJson = JSON.stringify(data.aliases);
      }
      
      let costJson = null;
      if (data.cost) {
        costJson = JSON.stringify(data.cost);
      }
      
      // 插入产品记录
      const insertSql = `
        INSERT INTO products (
          supplier_id, brand_id, category_id, name, description, code, image, sku, 
          aliases, level, cost, price, stock, logistics_status, logistics_details, 
          tracking_number, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
      `;
      
      const [result] = await connection.execute(insertSql, [
        data.supplierId || null,
        data.brandId || null,
        data.categoryId || null,
        data.name,
        data.description || null,
        data.code || null,
        data.image || null,
        data.sku || null,
        aliasesJson,
        data.level || null,
        costJson,
        data.price,
        data.stock || 0,
        data.logisticsStatus || null,
        data.logisticsDetails || null,
        data.trackingNumber || null
      ]);
      
      const insertId = (result as { insertId: number }).insertId;
      
      // 查询新插入的产品信息，包括关联的供应商、品牌、品类名称
      const [newProductRows] = await connection.query<ProductRow[]>(
        `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 = ?`,
        [insertId]
      );
      
      // 处理查询结果
      let newProduct: ProductRow | null = null;
      if (newProductRows.length > 0) {
        newProduct = newProductRows[0];
        
        // 处理JSON字段
        if (newProduct.aliases && typeof newProduct.aliases === 'string') {
          try {
            newProduct.aliases = JSON.parse(newProduct.aliases) as string[];
          } catch (error) {
            console.error('解析别名JSON失败:', error);
            newProduct.aliases = [] as string[];
          }
        }
        
        if (newProduct.cost && typeof newProduct.cost === 'string') {
          try {
            newProduct.cost = JSON.parse(newProduct.cost) as Record<string, number>;
          } catch (error) {
            console.error('解析成本JSON失败:', error);
            newProduct.cost = {} as Record<string, number>;
          }
        }
      }
      
      // 提交事务
      await connection.commit();
      
      console.log(`创建团队[${teamCode}]产品成功, ID:${insertId}`);
      
      return NextResponse.json({
        success: true,
        message: '产品创建成功',
        product: newProduct
      });
    } catch (error) {
      // 发生错误时回滚事务
      await connection.rollback();
      throw error;
    }
  } catch (error) {
    console.error(`创建团队[${teamCode}]产品失败:`, error);
    return NextResponse.json(
      { success: false, error: '创建产品失败' },
      { status: 500 }
    );
  }
};

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

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