import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseClient } from '@/storage/database/supabase-client';
import { registerCustomerSchema } 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/register - 客户注册
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证请求数据
    const validationResult = registerCustomerSchema.safeParse(body);
    if (!validationResult.success) {
      return NextResponse.json(
        { error: '数据验证失败', details: validationResult.error.issues },
        { status: 400 }
      );
    }
    
    const { name, phone, password, email, company } = validationResult.data;
    
    const client = getSupabaseClient();
    
    // 检查手机号是否已注册
    const { data: existingCustomer } = await client
      .from('customers')
      .select('id')
      .eq('phone', phone)
      .single();
    
    if (existingCustomer) {
      return NextResponse.json(
        { error: '该手机号已注册，请直接登录' },
        { status: 400 }
      );
    }
    
    // 哈希密码
    const hashedPassword = await hashPassword(password);
    
    // 创建客户
    const { data, error } = await client
      .from('customers')
      .insert({
        name,
        phone,
        password: hashedPassword,
        email: email || null,
        company: company || null,
      })
      .select()
      .single();
    
    if (error) {
      console.error('Error creating customer:', error);
      return NextResponse.json(
        { error: '注册失败，请稍后重试' },
        { status: 500 }
      );
    }
    
    // 设置登录状态 cookie（有效期7天）
    const cookieStore = await cookies();
    cookieStore.set('customer_id', data.id, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7, // 7天
      path: '/',
    });
    cookieStore.set('customer_phone', data.phone, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });
    cookieStore.set('customer_name', data.name, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: 60 * 60 * 24 * 7,
      path: '/',
    });
    
    // 返回客户信息（不包含密码）
    const customerData = {
      id: data.id,
      name: data.name,
      phone: data.phone,
      email: data.email,
      company: data.company,
      created_at: data.created_at,
      updated_at: data.updated_at,
    };
    
    return NextResponse.json({ 
      success: true, 
      customer: customerData,
      message: '注册成功！'
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
