/**
 * 单个品类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;
};

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

/**
 * 获取单个品类
 */
const getCategory = 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 
        id, name, description, icon, 
        created_at as createdAt, updated_at as updatedAt 
      FROM categories WHERE id = ?`,
      [id]
    );
    
    if (!Array.isArray(rows) || rows.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应品类' },
        { status: 404 }
      );
    }
    
    console.log(`查询团队[${teamCode}]品类成功, ID:${id}`);
    
    return NextResponse.json({
      success: true,
      category: rows[0]
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]品类详情失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取品类详情失败' },
      { status: 500 }
    );
  }
};

/**
 * 更新品类
 */
const updateCategory = 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 (!data.name && !data.description && !data.icon) {
    return NextResponse.json(
      { success: false, error: '缺少需要更新的字段' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始更新团队[${teamCode}]品类, ID:${id}`);
    
    // 使用数据库连接
    const connection = req.db;
    
    try {
      await connection.beginTransaction();
      
      // 检查品类是否存在
      const [existingCategory] = await connection.query(
        'SELECT id FROM categories WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingCategory) || existingCategory.length === 0) {
        await connection.rollback();
        return NextResponse.json(
          { success: false, error: '未找到相应品类' },
          { status: 404 }
        );
      }
      
      // 如果更新名称，检查名称是否已存在
      if (data.name) {
        const [nameCheck] = await connection.query(
          'SELECT id FROM categories WHERE name = ? AND id != ?',
          [data.name, id]
        );
        
        if (Array.isArray(nameCheck) && nameCheck.length > 0) {
          await connection.rollback();
          return NextResponse.json(
            { success: false, error: '该品类名称已存在' },
            { status: 409 }
          );
        }
      }
      
      // 构建更新SQL
      const updateFields = [];
      const updateParams = [];
      
      if (data.name) {
        updateFields.push('name = ?');
        updateParams.push(data.name);
      }
      
      if (data.description !== undefined) {
        updateFields.push('description = ?');
        updateParams.push(data.description || null);
      }
      
      if (data.icon !== undefined) {
        updateFields.push('icon = ?');
        updateParams.push(data.icon || null);
      }
      
      updateFields.push('updated_at = NOW()');
      
      // 添加ID作为WHERE条件参数
      updateParams.push(id);
      
      const updateSql = `
        UPDATE categories 
        SET ${updateFields.join(', ')} 
        WHERE id = ?
      `;
      
      await connection.query(updateSql, updateParams);
      
      // 查询更新后的品类信息
      const [updatedCategoryRows] = await connection.query(
        `SELECT 
          id, name, description, icon, 
          created_at as createdAt, updated_at as updatedAt 
        FROM categories WHERE id = ?`,
        [id]
      );
      
      // 提交事务
      await connection.commit();
      
      console.log(`更新团队[${teamCode}]品类成功, ID:${id}`);
      
      return NextResponse.json({
        success: true,
        message: '品类更新成功',
        category: Array.isArray(updatedCategoryRows) && updatedCategoryRows.length > 0 ? updatedCategoryRows[0] : null
      });
    } catch (error) {
      // 发生错误时回滚事务
      await connection.rollback();
      throw error;
    }
  } catch (error) {
    console.error(`更新团队[${teamCode}]品类失败:`, error);
    return NextResponse.json(
      { success: false, error: '更新品类失败' },
      { status: 500 }
    );
  }
};

/**
 * 删除品类
 */
const deleteCategory = 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 [existingCategory] = await req.db.query(
      'SELECT id FROM categories WHERE id = ?',
      [id]
    );
    
    if (!Array.isArray(existingCategory) || existingCategory.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应品类' },
        { status: 404 }
      );
    }
    
    // 直接删除品类记录
    await req.db.query('DELETE FROM categories 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(getCategory)(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(updateCategory)(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(deleteCategory)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理品类删除请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 