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

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

/**
 * 为请求添加团队信息
 * @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]/categories
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3的位置
  return pathParts[3] || '';
};

/**
 * GET 获取品类列表
 */
const getCategories = 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 offset = (page - 1) * pageSize;
  
  try {
    console.log(`开始查询团队[${teamCode}]品类列表, 页码:${page}, 每页:${pageSize}`);
    
    // 构建查询条件
    const conditions = [];
    const queryParams = [];
    
    if (keyword) {
      conditions.push('(name LIKE ? OR description LIKE ?)');
      queryParams.push(`%${keyword}%`, `%${keyword}%`);
    }
    
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    // 使用数据库连接
    const connection = req.db;
    
    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM categories ${whereClause}`;
    const [totalRows] = await connection.query(countSql, queryParams);
    
    const total = (totalRows as Array<{ total: number }>)[0].total;
    
    // 查询分页数据
    const querySql = `
      SELECT 
        id, name, description, icon, 
        created_at as createdAt, updated_at as updatedAt 
      FROM categories ${whereClause} 
      ORDER BY id ASC 
      LIMIT ? OFFSET ?
    `;
    
    // 添加分页参数
    const paginatedParams = [...queryParams, pageSize, offset];
    
    const [rows] = await connection.query(querySql, paginatedParams);
    
    console.log(`查询团队[${teamCode}]品类列表成功, 总数:${total}`);
    
    return NextResponse.json({
      success: true,
      total,
      categories: Array.isArray(rows) ? rows : []
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]品类列表失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取品类列表失败' },
      { status: 500 }
    );
  }
};

/**
 * POST 创建品类
 */
const createCategory = 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 }
    );
  }
  
  try {
    console.log(`开始创建团队[${teamCode}]品类, 名称:${data.name}`);
    
    // 使用数据库连接
    const connection = req.db;
    
    try {
      await connection.beginTransaction();
      
      // 检查品类名称是否已存在
      const [existingCategories] = await connection.query(
        'SELECT id FROM categories WHERE name = ?',
        [data.name]
      );
      
      if (Array.isArray(existingCategories) && existingCategories.length > 0) {
        await connection.rollback();
        return NextResponse.json(
          { success: false, error: '该品类名称已存在' },
          { status: 409 }
        );
      }
      
      // 插入品类记录
      const insertSql = `
        INSERT INTO categories (
          name, description, icon, created_at, updated_at
        ) VALUES (?, ?, ?, NOW(), NOW())
      `;
      
      const [result] = await connection.query(insertSql, [
        data.name,
        data.description || null,
        data.icon || null
      ]);
      
      const insertId = (result as { insertId: number }).insertId;
      
      // 查询新插入的品类信息
      const [newCategoryRows] = await connection.query(
        `SELECT 
          id, name, description, icon, 
          created_at as createdAt, updated_at as updatedAt 
         FROM categories WHERE id = ?`,
        [insertId]
      );
      
      // 提交事务
      await connection.commit();
      
      console.log(`创建团队[${teamCode}]品类成功, ID:${insertId}`);
      
      return NextResponse.json({
        success: true,
        message: '品类创建成功',
        category: Array.isArray(newCategoryRows) && newCategoryRows.length > 0 ? newCategoryRows[0] : null
      });
    } 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(getCategories)(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(createCategory)(teamReq, { teamCode });
  } catch (error) {
    console.error('处理品类创建请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 