/**
 * 品牌详情API路由
 * 作者: 阿瑞
 * 功能: 提供单个品牌数据的获取、更新和删除API
 * 版本: 2.1.0
 */

import { NextRequest, NextResponse } from 'next/server';
import { connectTeamDB, RequestWithDB } 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，因为它可能已被读取
    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]/brands/[id]
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3，品牌ID位于索引5
  return {
    teamCode: pathParts[3] || '',
    id: pathParts[5] || ''
  };
};

/**
 * 获取单个品牌详情
 * GET /api/team/[teamCode]/brands/[id]
 */
export async function GET(req: NextRequest) {
  try {
    // 从URL路径中提取参数
    const { teamCode, id } = extractParamsFromPath(req);
    
    // 验证参数
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    if (!id || isNaN(Number(id))) {
      return NextResponse.json(
        { success: false, error: '无效的品牌ID' },
        { status: 400 }
      );
    }
    
    // 处理函数
    const handler = async (dbReq: RequestWithDB) => {
      // 执行查询
      const [brands] = await dbReq.db.query(
        'SELECT id, `order`, name, description, created_at, updated_at FROM brands WHERE id = ?',
        [id]
      );
      
      // 检查是否找到品牌
      if (!Array.isArray(brands) || brands.length === 0) {
        return NextResponse.json(
          { success: false, error: '品牌不存在' },
          { status: 404 }
        );
      }
      
      return NextResponse.json({
        success: true,
        brand: brands[0] || null
      });
    };
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return await connectTeamDB(handler)(teamReq);
    
  } catch (error) {
    console.error('获取品牌详情失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '未知错误' 
      },
      { status: 500 }
    );
  }
}

/**
 * 更新品牌信息
 * PUT /api/team/[teamCode]/brands/[id]
 */
export async function PUT(req: NextRequest) {
  try {
    // 从URL路径中提取参数
    const { teamCode, id } = extractParamsFromPath(req);
    
    // 验证参数
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    if (!id || isNaN(Number(id))) {
      return NextResponse.json(
        { success: false, error: '无效的品牌ID' },
        { status: 400 }
      );
    }
    
    // 获取请求体数据
    let body;
    try {
      // 克隆请求，确保body只被读取一次
      const clonedReq = req.clone();
      body = await clonedReq.json();
      
      // 验证必填字段
      if (!body.name || body.name.trim() === '') {
        return NextResponse.json(
          { success: false, error: '品牌名称不能为空' },
          { status: 400 }
        );
      }
    } catch (error) {
      console.error('解析请求数据失败:', error);
      return NextResponse.json(
        { success: false, error: '无效的请求数据' },
        { status: 400 }
      );
    }
    
    // 处理函数
    const handler = async (dbReq: RequestWithDB) => {
      // 检查品牌是否存在
      const [existingBrands] = await dbReq.db.query(
        'SELECT id FROM brands WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingBrands) || existingBrands.length === 0) {
        return NextResponse.json(
          { success: false, error: '品牌不存在' },
          { status: 404 }
        );
      }
      
      // 准备更新数据
      const brandData = {
        name: body.name.trim(),
        order: typeof body.order === 'number' ? body.order : 0,
        description: body.description ? body.description.trim() : null
      };
      
      // 更新数据
      await dbReq.db.query(
        'UPDATE brands SET `order` = ?, name = ?, description = ? WHERE id = ?',
        [brandData.order, brandData.name, brandData.description, id]
      );
      
      // 获取更新后的品牌数据
      const [updatedBrands] = await dbReq.db.query(
        'SELECT id, `order`, name, description, created_at, updated_at FROM brands WHERE id = ?',
        [id]
      );
      
      return NextResponse.json({
        success: true,
        brand: Array.isArray(updatedBrands) && updatedBrands.length > 0 ? updatedBrands[0] : null,
        message: '品牌更新成功'
      });
    };
    
    // 添加团队信息到请求（不包含body）
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return await connectTeamDB(handler)(teamReq);
    
  } catch (error) {
    console.error('更新品牌失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '未知错误' 
      },
      { status: 500 }
    );
  }
}

/**
 * 删除品牌
 * DELETE /api/team/[teamCode]/brands/[id]
 */
export async function DELETE(req: NextRequest) {
  try {
    // 从URL路径中提取参数
    const { teamCode, id } = extractParamsFromPath(req);
    
    // 验证参数
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    if (!id || isNaN(Number(id))) {
      return NextResponse.json(
        { success: false, error: '无效的品牌ID' },
        { status: 400 }
      );
    }
    
    // 处理函数
    const handler = async (dbReq: RequestWithDB) => {
      // 检查品牌是否存在
      const [existingBrands] = await dbReq.db.query(
        'SELECT id FROM brands WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingBrands) || existingBrands.length === 0) {
        return NextResponse.json(
          { success: false, error: '品牌不存在' },
          { status: 404 }
        );
      }
      
      // 删除品牌
      await dbReq.db.query('DELETE FROM brands WHERE id = ?', [id]);
      
      return NextResponse.json({
        success: true,
        message: '品牌删除成功'
      });
    };
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return await connectTeamDB(handler)(teamReq);
    
  } catch (error) {
    console.error('删除品牌失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '未知错误' 
      },
      { status: 500 }
    );
  }
}; 