/**
 * 单个供应商API接口
 * 作者: 阿瑞
 * 功能: 提供单个供应商的查询、更新和删除接口
 * 版本: 2.0.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]/suppliers/[id]
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3，供应商ID位于索引5
  return {
    teamCode: pathParts[3] || '',
    id: pathParts[5] || ''
  };
};

/**
 * GET 获取单个供应商
 */
const getSupplier = 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, \`order\`, name, contact, status, level, type, remark,
        created_at as createdAt, updated_at as updatedAt 
      FROM suppliers 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,
      supplier: rows[0]
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]供应商详情失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取供应商详情失败' },
      { status: 500 }
    );
  }
};

/**
 * PUT 更新供应商
 */
const updateSupplier = 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 = await req.json();
  
  // 验证是否有需要更新的字段
  if (!data.name && data.order === undefined && !data.contact && data.status === undefined && 
      !data.level && !data.type && data.remark === undefined) {
    return NextResponse.json(
      { success: false, error: '缺少需要更新的字段' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始更新团队[${teamCode}]供应商, ID:${id}`);
    
    // 使用数据库连接并开始事务
    try {
      await req.db.beginTransaction();
      
      // 检查供应商是否存在
      const [existingSupplier] = await req.db.query(
        'SELECT id FROM suppliers WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingSupplier) || existingSupplier.length === 0) {
        await req.db.rollback();
        return NextResponse.json(
          { success: false, error: '未找到相应供应商' },
          { status: 404 }
        );
      }
      
      // 如果更新名称，检查名称是否已存在
      if (data.name) {
        const [nameCheck] = await req.db.query(
          'SELECT id FROM suppliers WHERE name = ? AND id != ?',
          [data.name, id]
        );
        
        if (Array.isArray(nameCheck) && nameCheck.length > 0) {
          await req.db.rollback();
          return NextResponse.json(
            { success: false, error: '该供应商名称已存在' },
            { status: 409 }
          );
        }
      }
      
      // 处理联系方式字段
      let contactJson = undefined;
      if (data.contact !== undefined) {
        contactJson = data.contact ? JSON.stringify(data.contact) : null;
      }
      
      // 构建更新SQL
      const updateFields = [];
      const updateParams = [];
      
      if (data.name) {
        updateFields.push('name = ?');
        updateParams.push(data.name);
      }
      
      if (data.order !== undefined) {
        updateFields.push('`order` = ?');
        updateParams.push(data.order);
      }
      
      if (contactJson !== undefined) {
        updateFields.push('contact = ?');
        updateParams.push(contactJson);
      }
      
      if (data.status !== undefined) {
        updateFields.push('status = ?');
        updateParams.push(data.status);
      }
      
      if (data.level !== undefined) {
        updateFields.push('level = ?');
        updateParams.push(data.level || null);
      }
      
      if (data.type !== undefined) {
        updateFields.push('type = ?');
        updateParams.push(data.type || null);
      }
      
      if (data.remark !== undefined) {
        updateFields.push('remark = ?');
        updateParams.push(data.remark || null);
      }
      
      updateFields.push('updated_at = NOW()');
      
      // 添加ID作为WHERE条件参数
      updateParams.push(id);
      
      const updateSql = `
        UPDATE suppliers 
        SET ${updateFields.join(', ')} 
        WHERE id = ?
      `;
      
      await req.db.query(updateSql, updateParams);
      
      // 查询更新后的供应商信息
      const [updatedSupplierRows] = await req.db.query(
        `SELECT 
          id, \`order\`, name, contact, status, level, type, remark,
          created_at as createdAt, updated_at as updatedAt 
        FROM suppliers WHERE id = ?`,
        [id]
      );
      
      // 提交事务
      await req.db.commit();
      
      console.log(`更新团队[${teamCode}]供应商成功, ID:${id}`);
      
      return NextResponse.json({
        success: true,
        message: '供应商更新成功',
        supplier: Array.isArray(updatedSupplierRows) && updatedSupplierRows.length > 0 ? updatedSupplierRows[0] : null
      });
    } catch (error) {
      // 发生错误时回滚事务
      await req.db.rollback();
      throw error;
    }
  } catch (error) {
    console.error(`更新团队[${teamCode}]供应商失败:`, error);
    return NextResponse.json(
      { success: false, error: '更新供应商失败' },
      { status: 500 }
    );
  }
};

/**
 * DELETE 删除供应商
 */
const deleteSupplier = 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}`);
    
    // 使用数据库连接执行删除操作
    try {
      await req.db.beginTransaction();
      
      // 检查供应商是否存在
      const [existingSupplier] = await req.db.query(
        'SELECT id FROM suppliers WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingSupplier) || existingSupplier.length === 0) {
        await req.db.rollback();
        return NextResponse.json(
          { success: false, error: '未找到相应供应商' },
          { status: 404 }
        );
      }
      
      // 删除供应商与品类的关联记录
      await req.db.query('DELETE FROM supplier_categories WHERE supplier_id = ?', [id]);
      
      // 删除供应商记录
      await req.db.query('DELETE FROM suppliers WHERE id = ?', [id]);
      
      // 提交事务
      await req.db.commit();
      
      console.log(`删除团队[${teamCode}]供应商成功, ID:${id}`);
      
      return NextResponse.json({
        success: true,
        message: '供应商删除成功'
      });
    } catch (error) {
      // 发生错误时回滚事务
      await req.db.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, id } = extractParamsFromPath(req);
    
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return connectTeamDB(getSupplier)(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 }
      );
    }
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return connectTeamDB(updateSupplier)(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(deleteSupplier)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理供应商删除请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 