/**
 * 单个支付平台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，因为它可能已被读取
    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]/payment-platforms/[id]
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3，支付平台ID位于索引5
  return {
    teamCode: pathParts[3] || '',
    id: pathParts[5] || ''
  };
};

/**
 * 获取单个支付平台
 */
const getPaymentPlatform = 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, description, status,
        created_at as createdAt, updated_at as updatedAt 
      FROM payment_platforms 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,
      paymentPlatform: rows[0]
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]支付平台详情失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取支付平台详情失败' },
      { status: 500 }
    );
  }
};

/**
 * 更新支付平台
 */
interface PaymentPlatformRequestBody {
  id?: number;
  name?: string;
  order?: number;
  description?: string | null;
  status?: number;
}

const updatePaymentPlatform = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  const teamCode = params?.teamCode as string;
  const data = params?.requestBody as PaymentPlatformRequestBody;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的支付平台ID' },
      { status: 400 }
    );
  }
  
  if (!data) {
    return NextResponse.json(
      { success: false, error: '请求数据为空' },
      { status: 400 }
    );
  }
  
  // 验证是否有需要更新的字段
  if (!data.name && data.order === undefined && !data.description && data.status === undefined) {
    return NextResponse.json(
      { success: false, error: '缺少需要更新的字段' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始更新团队[${teamCode}]支付平台, ID:${id}`);
    
    // 使用数据库连接
    const connection = req.db;
    
    try {
      await connection.beginTransaction();
      
      // 检查支付平台是否存在
      const [existingPlatform] = await connection.query(
        'SELECT id FROM payment_platforms WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingPlatform) || existingPlatform.length === 0) {
        await connection.rollback();
        return NextResponse.json(
          { success: false, error: '未找到相应支付平台' },
          { status: 404 }
        );
      }
      
      // 如果更新名称，检查名称是否已存在
      if (data.name) {
        const [nameCheck] = await connection.query(
          'SELECT id FROM payment_platforms 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.order !== undefined) {
        updateFields.push('`order` = ?');
        updateParams.push(data.order);
      }
      
      if (data.description !== undefined) {
        updateFields.push('description = ?');
        updateParams.push(data.description || null);
      }
      
      if (data.status !== undefined) {
        updateFields.push('status = ?');
        updateParams.push(data.status);
      }
      
      updateFields.push('updated_at = NOW()');
      
      // 添加ID作为WHERE条件参数
      updateParams.push(id);
      
      const updateSql = `
        UPDATE payment_platforms 
        SET ${updateFields.join(', ')} 
        WHERE id = ?
      `;
      
      await connection.query(updateSql, updateParams);
      
      // 查询更新后的支付平台信息
      const [updatedPlatformRows] = await connection.query(
        `SELECT 
          id, \`order\`, name, description, status,
          created_at as createdAt, updated_at as updatedAt 
        FROM payment_platforms WHERE id = ?`,
        [id]
      );
      
      // 提交事务
      await connection.commit();
      
      console.log(`更新团队[${teamCode}]支付平台成功, ID:${id}`);
      
      return NextResponse.json({
        success: true,
        message: '支付平台更新成功',
        paymentPlatform: Array.isArray(updatedPlatformRows) && updatedPlatformRows.length > 0 ? updatedPlatformRows[0] : null
      });
    } catch (error) {
      // 发生错误时回滚事务
      await connection.rollback();
      throw error;
    }
  } catch (error) {
    console.error(`更新团队[${teamCode}]支付平台失败:`, error);
    return NextResponse.json(
      { success: false, error: '更新支付平台失败' },
      { status: 500 }
    );
  }
};

/**
 * 删除支付平台
 */
const deletePaymentPlatform = 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 [existingPlatform] = await req.db.query(
      'SELECT id FROM payment_platforms WHERE id = ?',
      [id]
    );
    
    if (!Array.isArray(existingPlatform) || existingPlatform.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应支付平台' },
        { status: 404 }
      );
    }
    
    // 直接删除支付平台记录
    await req.db.query('DELETE FROM payment_platforms 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(getPaymentPlatform)(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 }
      );
    }
    
    // 先读取请求体
    let requestBody;
    try {
      // 克隆请求，确保body只被读取一次
      const clonedReq = req.clone();
      requestBody = await clonedReq.json();
    } catch (error) {
      console.error('解析请求数据失败:', error);
      return NextResponse.json(
        { success: false, error: '无效的请求数据格式' },
        { status: 400 }
      );
    }
    
    // 添加团队信息到请求（不传递body）
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return connectTeamDB(updatePaymentPlatform)(teamReq, { teamCode, id, requestBody });
  } 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(deletePaymentPlatform)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理支付平台删除请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 