/**
 * 客户详情API路由
 * 作者: 阿瑞
 * 功能: 提供单个客户数据的获取、更新和删除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]/customers/[id]
  const pathParts = req.nextUrl.pathname.split('/');
  // 团队代码位于索引3，客户ID位于索引5
  return {
    teamCode: pathParts[3] || '',
    id: pathParts[5] || ''
  };
};

/**
 * 获取单个客户详情
 */
const getCustomerDetail = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的客户ID' },
      { status: 400 }
    );
  }
  
  try {
    // 查询客户信息
    const [rows] = await req.db.query(
      `SELECT 
        id, name, phone, gender, wechat, 
        address, birthday, follow_date as followDate, balance,
        created_at as createdAt, updated_at as updatedAt 
       FROM customers 
       WHERE id = ? AND deleted_at IS NULL`,
      [id]
    );
    
    if (!Array.isArray(rows) || rows.length === 0) {
      return NextResponse.json(
        { success: false, error: '客户不存在' },
        { status: 404 }
      );
    }
    
    return NextResponse.json({
      success: true,
      customer: rows[0]
    });
  } catch (error) {
    console.error('获取客户详情失败:', error);
    return NextResponse.json(
      { success: false, error: '获取客户详情失败' },
      { status: 500 }
    );
  }
};

/**
 * 更新客户信息
 */
interface CustomerRequestBody {
  id?: number;
  name?: string;
  phone?: string;
  gender?: number;
  wechat?: string;
  birthday?: string;
  followDate?: string;
  balance?: number;
  address?: string | null | {
    province?: string | null;
    city?: string | null;
    district?: string | null;
    county?: string | null;
    detail?: string | null;
  };
  [key: string]: unknown; // 索引签名允许动态访问属性
}

const updateCustomer = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  const data = params?.requestBody as CustomerRequestBody;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的客户ID' },
      { status: 400 }
    );
  }
  
  if (!data) {
    return NextResponse.json(
      { success: false, error: '请求数据为空' },
      { status: 400 }
    );
  }
  
  // 验证ID是否匹配
  if (data.id !== undefined && data.id !== Number(id)) {
    return NextResponse.json(
      { success: false, error: '客户ID不匹配' },
      { status: 400 }
    );
  }
  
  try {
    // 检查客户是否存在
    const [existingCustomers] = await req.db.query(
      'SELECT id FROM customers WHERE id = ? AND deleted_at IS NULL',
      [id]
    );
    
    if (!Array.isArray(existingCustomers) || existingCustomers.length === 0) {
      return NextResponse.json(
        { success: false, error: '客户不存在' },
        { status: 404 }
      );
    }
    
    // 如果更新手机号，检查是否与其他客户重复
    if (data.phone) {
      const [phoneCheck] = await req.db.query(
        'SELECT id FROM customers WHERE phone = ? AND id != ? AND deleted_at IS NULL',
        [data.phone, id]
      );
      
      if (Array.isArray(phoneCheck) && phoneCheck.length > 0) {
        return NextResponse.json(
          { success: false, error: '该手机号已被其他客户使用' },
          { status: 409 }
        );
      }
    }
    
    // 处理地址字段，确保正确存储结构化地址
    let addressJson: string | null = null;
    if (data.address !== undefined) {
      if (data.address === null) {
        addressJson = null;
      } else {
        // 标准化地址对象结构
        const addressObj: {
          province: string | null;
          city: string | null;
          district: string | null;
          detail: string | null;
        } = {
          province: null,
          city: null, 
          district: null,
          detail: null
        };
        
        if (typeof data.address === 'string') {
          // 如果是字符串，作为详细地址存储
          addressObj.detail = data.address;
        } else if (typeof data.address === 'object' && data.address !== null) {
          // 将提供的地址对象结构化
          const addrObj = data.address as {
            province?: string | null;
            city?: string | null;
            district?: string | null;
            county?: string | null;
            detail?: string | null;
          };
          if (addrObj.province) addressObj.province = addrObj.province;
          if (addrObj.city) addressObj.city = addrObj.city;
          if (addrObj.district || addrObj.county) {
            addressObj.district = addrObj.district || addrObj.county || null;
          }
          if (addrObj.detail) addressObj.detail = addrObj.detail;
        }
        
        // 只有当至少有一个地址字段有值时才存储地址
        if (addressObj.province || addressObj.city || addressObj.district || addressObj.detail) {
          addressJson = JSON.stringify(addressObj);
        } else {
          addressJson = null;
        }
      }
    }
    
    // 构建更新字段
    const updateFields: string[] = [];
    const updateValues: (string | number | null)[] = [];
    
    // 可更新的字段列表
    const fieldMapping: Record<string, string> = {
      'name': 'name',
      'phone': 'phone',
      'gender': 'gender',
      'wechat': 'wechat',
      'birthday': 'birthday',
      'followDate': 'follow_date',
      'balance': 'balance'
    };
    
    // 特殊处理地址字段
    if (addressJson !== undefined) {
      updateFields.push('address = ?');
      updateValues.push(addressJson);
    }
    
    // 遍历请求数据，构建更新语句
    Object.entries(fieldMapping).forEach(([clientField, dbField]) => {
      if (data[clientField] !== undefined) {
        updateFields.push(`${dbField} = ?`);
        
        // 特殊处理日期字段，空字符串转为NULL
        if ((clientField === 'birthday' || clientField === 'followDate') && data[clientField] === '') {
          updateValues.push(null);
        } else {
          const value = data[clientField];
          // 类型安全处理：确保值为string、number或null
          if (typeof value === 'object' && value !== null) {
            updateValues.push(null);
          } else {
            updateValues.push(value as string | number | null);
          }
        }
      }
    });
    
    // 添加更新时间
    updateFields.push('updated_at = NOW()');
    
    // 如果没有要更新的字段，返回成功
    if (updateFields.length === 0) {
      return NextResponse.json({
        success: true,
        message: '无需更新'
      });
    }
    
    // 构建并执行更新SQL
    const updateSql = `UPDATE customers SET ${updateFields.join(', ')} WHERE id = ?`;
    updateValues.push(id);
    
    await req.db.query(updateSql, updateValues);
    
    // 获取更新后的客户信息
    const [updatedRows] = await req.db.query(
      `SELECT 
        id, name, phone, gender, wechat, 
        address, birthday, follow_date as followDate, balance,
        created_at as createdAt, updated_at as updatedAt 
       FROM customers 
       WHERE id = ?`,
      [id]
    );
    
    return NextResponse.json({
      success: true,
      message: '客户更新成功',
      customer: Array.isArray(updatedRows) && updatedRows.length > 0 ? updatedRows[0] : null
    });
  } catch (error) {
    console.error('更新客户失败:', error);
    return NextResponse.json(
      { success: false, error: '更新客户失败' },
      { status: 500 }
    );
  }
};

/**
 * 删除客户
 */
const deleteCustomer = async (req: RequestWithDB, params?: Record<string, unknown>) => {
  const id = params?.id as string;
  
  if (!id || isNaN(Number(id))) {
    return NextResponse.json(
      { success: false, error: '无效的客户ID' },
      { status: 400 }
    );
  }
  
  try {
    // 检查客户是否存在
    const [existingCustomers] = await req.db.query(
      'SELECT id FROM customers WHERE id = ? AND deleted_at IS NULL',
      [id]
    );
    
    if (!Array.isArray(existingCustomers) || existingCustomers.length === 0) {
      return NextResponse.json(
        { success: false, error: '客户不存在' },
        { status: 404 }
      );
    }
    
    // 软删除：设置deleted_at字段
    await req.db.query(
      'UPDATE customers SET deleted_at = NOW(), updated_at = NOW() WHERE id = ?',
      [id]
    );
    
    return NextResponse.json({
      success: true,
      message: '客户删除成功'
    });
  } catch (error) {
    console.error('删除客户失败:', 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(getCustomerDetail)(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(updateCustomer)(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(deleteCustomer)(teamReq, { teamCode, id });
  } catch (error) {
    console.error('处理客户删除请求失败:', error);
    return NextResponse.json(
      { success: false, error: '处理请求失败' },
      { status: 500 }
    );
  }
} 