import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';
import { loginCustomerSchema } from '@/storage/database/shared/schema';
import { cookies } from 'next/headers';

// 密码哈希函数（使用 Web Crypto API）
async function hashPassword(password: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(password);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// POST /api/auth/login - 客户登录
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证请求数据
    const validationResult = loginCustomerSchema.safeParse(body);
    if (!validationResult.success) {
      return NextResponse.json(
        { error: '数据验证失败', details: validationResult.error.issues },
        { status: 400 }
      );
    }
    
    const { phone, password } = validationResult.data;
    
    const client = getSupabaseClient();
    
    // 查找客户
    const { data: customer, error } = await client
      .from('customers')
      .select('*')
      .eq('phone', phone)
      .single();
    
    if (error || !customer) {
      return NextResponse.json(
        { error: '手机号或密码错误' },
        { status: 401 }
      );
    }
    
    // 验证密码
    const hashedPassword = await hashPassword(password);
    if (customer.password !== hashedPassword) {
      return NextResponse.json(
        { error: '手机号或密码错误' },
        { status: 401 }
      );
    }
    
    // 设置登录状态 cookie（有效期7天）
    const cookieStore = await cookies();
    cookieStore.set('customer_id', customer.id, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7, // 7天
      path: '/',
    });
    cookieStore.set('customer_phone', customer.phone, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });
    cookieStore.set('customer_name', customer.name, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });
    
    // 返回客户信息（不包含密码）
    const customerData = {
      id: customer.id,
      name: customer.name,
      phone: customer.phone,
      email: customer.email,
      company: customer.company,
      created_at: customer.created_at,
      updated_at: customer.updated_at,
    };
    
    return NextResponse.json({ 
      success: true, 
      customer: customerData,
      message: '登录成功！'
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
