/**
 * 单个店铺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]/shops/[id]
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3，店铺ID位于索引5
  return {
    teamCode: pathParts[3] || '',
    id: pathParts[5] || ''
  };
};

/**
 * 获取单个店铺
 */
const getShop = 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, unionid, openid, account_no as accountNo, wechat,
        avatar, nickname, phone, status, remark,
        created_at as createdAt, updated_at as updatedAt 
      FROM shops 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,
      shop: rows[0]
    });
  } catch (error) {
    console.error(`获取团队[${teamCode}]店铺详情失败:`, error);
    return NextResponse.json(
      { success: false, error: '获取店铺详情失败' },
      { status: 500 }
    );
  }
};

/**
 * 更新店铺
 */
interface ShopRequestBody {
  id?: number;
  unionid?: string | null;
  openid?: string | null;
  accountNo?: string | null;
  wechat?: string | null;
  avatar?: string | null;
  nickname?: string | null;
  phone?: string | null;
  status?: number;
  remark?: string | null;
}

const updateShop = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  const teamCode = params?.teamCode as string;
  const data = params?.requestBody as ShopRequestBody;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的店铺ID' },
      { status: 400 }
    );
  }
  
  if (!data) {
    return NextResponse.json(
      { success: false, error: '请求数据为空' },
      { status: 400 }
    );
  }
  
  try {
    console.log(`开始更新团队[${teamCode}]店铺, ID:${id}`);
    
    // 使用数据库连接
    const connection = req.db;
    
    try {
      await connection.beginTransaction();
      
      // 检查店铺是否存在
      const [existingShop] = await connection.query(
        'SELECT id FROM shops WHERE id = ?',
        [id]
      );
      
      if (!Array.isArray(existingShop) || existingShop.length === 0) {
        await connection.rollback();
        return NextResponse.json(
          { success: false, error: '未找到相应店铺' },
          { status: 404 }
        );
      }
      
      // 如果更新unionid，检查是否已存在
      if (data.unionid) {
        const [unionidCheck] = await connection.query(
          'SELECT id FROM shops WHERE unionid = ? AND id != ?',
          [data.unionid, id]
        );
        
        if (Array.isArray(unionidCheck) && unionidCheck.length > 0) {
          await connection.rollback();
          return NextResponse.json(
            { success: false, error: '该unionid已存在' },
            { status: 409 }
          );
        }
      }
      
      // 如果更新wechat，检查是否已存在
      if (data.wechat) {
        const [wechatCheck] = await connection.query(
          'SELECT id FROM shops WHERE wechat = ? AND id != ?',
          [data.wechat, id]
        );
        
        if (Array.isArray(wechatCheck) && wechatCheck.length > 0) {
          await connection.rollback();
          return NextResponse.json(
            { success: false, error: '该微信号已存在' },
            { status: 409 }
          );
        }
      }
      
      // 构建更新SQL
      const updateFields = [];
      const updateParams = [];
      
      // 按字段顺序检查并添加到更新列表
      if (data.unionid !== undefined) {
        updateFields.push('unionid = ?');
        updateParams.push(data.unionid || null);
      }
      
      if (data.openid !== undefined) {
        updateFields.push('openid = ?');
        updateParams.push(data.openid || null);
      }
      
      if (data.accountNo !== undefined) {
        updateFields.push('account_no = ?');
        updateParams.push(data.accountNo || null);
      }
      
      if (data.wechat !== undefined) {
        updateFields.push('wechat = ?');
        updateParams.push(data.wechat || null);
      }
      
      if (data.avatar !== undefined) {
        updateFields.push('avatar = ?');
        updateParams.push(data.avatar || null);
      }
      
      if (data.nickname !== undefined) {
        updateFields.push('nickname = ?');
        updateParams.push(data.nickname || null);
      }
      
      if (data.phone !== undefined) {
        updateFields.push('phone = ?');
        updateParams.push(data.phone || null);
      }
      
      if (data.status !== undefined) {
        updateFields.push('status = ?');
        updateParams.push(data.status);
      }
      
      if (data.remark !== undefined) {
        updateFields.push('remark = ?');
        updateParams.push(data.remark || null);
      }
      
      if (updateFields.length === 0) {
        await connection.rollback();
        return NextResponse.json(
          { success: false, error: '没有提供需要更新的字段' },
          { status: 400 }
        );
      }
      
      updateFields.push('updated_at = NOW()');
      
      // 添加ID作为WHERE条件参数
      updateParams.push(id);
      
      const updateSql = `
        UPDATE shops 
        SET ${updateFields.join(', ')} 
        WHERE id = ?
      `;
      
      await connection.query(updateSql, updateParams);
      
      // 查询更新后的店铺信息
      const [updatedShopRows] = await connection.query(
        `SELECT 
          id, unionid, openid, account_no as accountNo, wechat,
          avatar, nickname, phone, status, remark,
          created_at as createdAt, updated_at as updatedAt 
        FROM shops WHERE id = ?`,
        [id]
      );
      
      // 提交事务
      await connection.commit();
      
      console.log(`更新团队[${teamCode}]店铺成功, ID:${id}`);
      
      return NextResponse.json({
        success: true,
        message: '店铺更新成功',
        shop: Array.isArray(updatedShopRows) && updatedShopRows.length > 0 ? updatedShopRows[0] : null
      });
    } catch (error) {
      // 发生错误时回滚事务
      await connection.rollback();
      throw error;
    }
  } catch (error) {
    console.error(`更新团队[${teamCode}]店铺失败:`, error);
    return NextResponse.json(
      { success: false, error: '更新店铺失败' },
      { status: 500 }
    );
  }
};

/**
 * 删除店铺
 */
const deleteShop = 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 [existingShop] = await req.db.query(
      'SELECT id FROM shops WHERE id = ?',
      [id]
    );
    
    if (!Array.isArray(existingShop) || existingShop.length === 0) {
      return NextResponse.json(
        { success: false, error: '未找到相应店铺' },
        { status: 404 }
      );
    }
    
    // 直接删除店铺记录
    await req.db.query('DELETE FROM shops 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(getShop)(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(updateShop)(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(deleteShop)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理店铺删除请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 