/**
 * 店铺粉丝增长统计API路由
 * 作者: 阿瑞
 * 功能: 提供店铺粉丝增长的统计分析数据
 * 版本: 2.0.0
 */

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

/**
 * 为请求添加团队信息
 * @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;
};

/**
 * 从请求路径中提取团队代码
 * @param req 请求对象
 * @returns 团队代码
 */
const extractTeamCodeFromPath = (req: NextRequest): string => {
  // 路径格式: /api/team/[teamCode]/shop-follower-growth/statistics
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3的位置
  return pathParts[3] || '';
};

/**
 * 获取店铺粉丝增长统计数据
 */
const getGrowthStatistics = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const teamCode = params?.teamCode as string;
  const { searchParams } = new URL(req.url);
  
  // 获取查询参数
  const shopIds = searchParams.getAll('shopIds');
  const startDate = searchParams.get('startDate');
  const endDate = searchParams.get('endDate');
  
  if (!shopIds || shopIds.length === 0) {
    return NextResponse.json(
      { success: false, error: '请提供至少一个店铺ID' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始查询团队[${teamCode}]店铺粉丝增长统计数据`);
    
    // 构建查询条件
    const conditions = ['1=1']; // 始终为真的条件，方便后续拼接
    const queryParams: (string | number)[] = [];
    
    // 添加店铺ID过滤
    if (shopIds.length > 0) {
      const shopIdsInt = shopIds.map(id => parseInt(id));
      conditions.push(`g.shop_id IN (${shopIdsInt.map(() => '?').join(',')})`);
      queryParams.push(...shopIdsInt);
    }
    
    // 添加时间范围过滤
    if (startDate) {
      conditions.push('g.date >= ?');
      queryParams.push(startDate);
    }
    
    if (endDate) {
      conditions.push('g.date <= ?');
      queryParams.push(endDate);
    }
    
    // 拼接条件
    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    
    // 使用数据库连接
    const connection = req.db;
    
    // 查询数据
    const [rows] = await connection.query<RowDataPacket[]>(
      `SELECT 
         g.shop_id, g.date, g.total, g.deducted, g.daily_increase,
         s.wechat, s.nickname
       FROM shop_follower_growth g
       LEFT JOIN shops s ON g.shop_id = s.id
       ${whereClause}
       ORDER BY g.shop_id, g.date`,
      queryParams
    );
    
    // 按店铺分组处理数据
    const shopGroups: Record<number, {
      shop_id: number;
      shop_name: string;
      dates: string[];
      total_counts: number[];
      daily_increases: number[];
    }> = {};
    
    if (Array.isArray(rows)) {
      rows.forEach(row => {
        const shopId = row.shop_id;
        
        if (!shopGroups[shopId]) {
          shopGroups[shopId] = {
            shop_id: shopId,
            shop_name: row.nickname || row.wechat || `店铺ID: ${shopId}`,
            dates: [],
            total_counts: [],
            daily_increases: []
          };
        }
        
        shopGroups[shopId].dates.push(row.date.toISOString().split('T')[0]);
        shopGroups[shopId].total_counts.push(row.total);
        shopGroups[shopId].daily_increases.push(row.daily_increase);
      });
    }
    
    // 转换为数组
    const statistics = Object.values(shopGroups);
    
    console.log(`查询团队[${teamCode}]店铺粉丝增长统计数据成功，共 ${statistics.length} 个店铺的数据`);
    
    return NextResponse.json({
      success: true,
      statistics
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]店铺粉丝增长统计数据失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取店铺粉丝增长统计数据失败' },
      { status: 500 }
    );
  }
};

// 导出处理函数
export async function GET(req: NextRequest) {
  try {
    // 从URL路径中提取团队代码
    const teamCode = extractTeamCodeFromPath(req);
    
    if (!teamCode) {
      return NextResponse.json(
        { success: false, error: '无效的团队代码' },
        { status: 400 }
      );
    }
    
    // 添加团队信息到请求
    const teamReq = addTeamInfoToRequest(req, teamCode);
    
    // 使用新版的connectTeamDB中间件处理请求
    return connectTeamDB(getGrowthStatistics)(teamReq, { teamCode });
  } catch (error) {
    console.error('处理店铺粉丝增长统计请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 