/**
 * 单个店铺粉丝增长记录API路由
 * 作者: 阿瑞
 * 功能: 提供单个店铺粉丝增长记录的获取、更新和删除接口
 * 版本: 2.0.0
 */

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

// 定义数据类型接口
interface ShopRecord extends RowDataPacket {
  id: number;
  shop_id: number;
  date: Date;
  total: number;
  deducted: number;
  daily_increase: number;
  created_at: Date;
  updated_at: Date;
  wechat?: string;
  nickname?: string;
}

/**
 * 为请求添加团队信息
 * @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]/shop-follower-growth/[id]
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3，记录ID位于索引5
  return {
    teamCode: pathParts[3] || '',
    id: pathParts[5] || ''
  };
};

/**
 * 格式化MySQL日期为YYYY-MM-DD格式
 * 修复时区问题，保留原始日期
 */
function formatMySQLDate(date: Date): string {
  // MySQL中存储的是本地日期，直接获取日期部分即可
  // 注意：不使用toISOString()，因为它会转换为UTC时间并导致日期偏移
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/**
 * 获取单个店铺粉丝增长记录
 */
const getGrowthRecord = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const teamCode = params?.teamCode as string;
  const id = params?.id 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<ShopRecord[]>(
      `SELECT 
         g.id, g.shop_id, g.date, g.total, g.deducted, g.daily_increase,
         g.created_at, g.updated_at,
         s.wechat, s.nickname
       FROM shop_follower_growth g
       LEFT JOIN shops s ON g.shop_id = s.id
       WHERE g.id = ?`,
      [id]
    );
    
    if (!Array.isArray(rows) || rows.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应记录' },
        { status: 404 }
      );
    }
    
    // 格式化返回数据
    const record = {
      id: rows[0].id,
      shop_id: rows[0].shop_id,
      date: formatMySQLDate(rows[0].date), // 使用修复的日期格式化函数
      total: rows[0].total,
      deducted: rows[0].deducted,
      daily_increase: rows[0].daily_increase,
      created_at: rows[0].created_at,
      updated_at: rows[0].updated_at,
      shop_name: rows[0].nickname || rows[0].wechat || `店铺ID: ${rows[0].shop_id}`
    };
    
    console.log(`查询团队[${teamCode}]店铺粉丝增长记录成功, ID:${id}`);
    
    return NextResponse.json({
      success: true,
      record
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]店铺粉丝增长记录详情失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取粉丝增长记录详情失败' },
      { status: 500 }
    );
  }
};

/**
 * 更新店铺粉丝增长记录
 */
const updateGrowthRecord = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const teamCode = params?.teamCode as string;
  const id = params?.id as string;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的记录ID' },
      { status: 400 }
    );
  }
  
  try {
    // 解析请求数据或使用预解析的数据
    const data = req.parsedBody || await req.json();
    const { shop_id, date, total, deducted } = data;
    
    // 验证必填字段
    if (!shop_id || !date || total === undefined) {
      return NextResponse.json(
        { success: false, error: '店铺ID、日期和粉丝总数为必填项' },
        { status: 400 }
      );
    }
    
    // 验证数据类型
    if (typeof shop_id !== 'number' || typeof total !== 'number') {
      return NextResponse.json(
        { success: false, error: '数据类型错误' },
        { status: 400 }
      );
    }
    
    // 使用数据库连接
    const connection = req.db;
    
    // 检查记录是否存在
    const [existingRecord] = await connection.query<RowDataPacket[]>(
      'SELECT id FROM shop_follower_growth WHERE id = ?',
      [id]
    );
    
    if (!Array.isArray(existingRecord) || existingRecord.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应记录' },
        { status: 404 }
      );
    }
    
    // 检查店铺是否存在
    const [shopExists] = await connection.query<RowDataPacket[]>(
      'SELECT id FROM shops WHERE id = ?',
      [shop_id]
    );
    
    if (!Array.isArray(shopExists) || shopExists.length === 0) {
      return NextResponse.json(
        { success: false, error: '店铺不存在' },
        { status: 400 }
      );
    }
    
    // 检查日期是否与其他记录冲突
    const [dateConflict] = await connection.query<RowDataPacket[]>(
      'SELECT id FROM shop_follower_growth WHERE shop_id = ? AND date = ? AND id != ?',
      [shop_id, date, id]
    );
    
    if (Array.isArray(dateConflict) && dateConflict.length > 0) {
      return NextResponse.json(
        { success: false, error: '该店铺在选定日期已有其他记录，一个店铺每天只能有一条记录' },
        { status: 409 }
      );
    }
    
    // 计算日增长
    const daily_increase = total - (deducted || 0);
    
    // 更新记录
    await connection.query(
      `UPDATE shop_follower_growth
       SET shop_id = ?, date = ?, total = ?, deducted = ?, daily_increase = ?
       WHERE id = ?`,
      [shop_id, date, total, deducted || 0, daily_increase, id]
    );
    
    console.log(`更新团队[${teamCode}]店铺粉丝增长记录成功, ID:${id}`);
    
    // 返回更新后的数据
    return NextResponse.json({
      success: true,
      record: {
        id: parseInt(id),
        shop_id,
        date,
        total,
        deducted: deducted || 0,
        daily_increase
      }
    });
  } catch (error) {
    console.error(`更新团队[${teamCode}]店铺粉丝增长记录失败:`, error);
    return NextResponse.json(
      { success: false, error: '更新粉丝增长记录失败' },
      { status: 500 }
    );
  }
};

/**
 * 删除店铺粉丝增长记录
 */
const deleteGrowthRecord = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const teamCode = params?.teamCode as string;
  const id = params?.id as string;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的记录ID' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始删除团队[${teamCode}]店铺粉丝增长记录, ID:${id}`);
    
    // 使用数据库连接
    const connection = req.db;
    
    // 检查记录是否存在
    const [existingRecord] = await connection.query<RowDataPacket[]>(
      'SELECT id FROM shop_follower_growth WHERE id = ?',
      [id]
    );
    
    if (!Array.isArray(existingRecord) || existingRecord.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应记录' },
        { status: 404 }
      );
    }
    
    // 删除记录
    await connection.query(
      'DELETE FROM shop_follower_growth 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(getGrowthRecord)(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(updateGrowthRecord)(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(deleteGrowthRecord)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理粉丝增长记录删除请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 