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

const supabase = getSupabaseClient();

// 更新用户资料
export async function PUT(request: NextRequest) {
  try {
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;

    if (!customerId) {
      return NextResponse.json(
        { error: '未登录' },
        { status: 401 }
      );
    }

    const body = await request.json();
    const { name, phone, company } = body;

    // 验证必填字段
    if (!name || !phone) {
      return NextResponse.json(
        { error: '姓名和手机号为必填项' },
        { status: 400 }
      );
    }

    // 验证手机号格式
    if (!/^\d{11}$/.test(phone)) {
      return NextResponse.json(
        { error: '手机号格式不正确' },
        { status: 400 }
      );
    }

    // 检查手机号是否已被其他用户使用
    const { data: existingCustomer, error: checkError } = await supabase
      .from('customers')
      .select('id')
      .eq('phone', phone)
      .neq('id', customerId)
      .single();

    if (existingCustomer) {
      return NextResponse.json(
        { error: '该手机号已被其他用户使用' },
        { status: 400 }
      );
    }

    // 更新用户资料
    const { data: customer, error: updateError } = await supabase
      .from('customers')
      .update({
        name,
        phone,
        company: company || null,
        updated_at: new Date().toISOString(),
      })
      .eq('id', customerId)
      .select()
      .single();

    if (updateError) {
      console.error('Update error:', updateError);
      return NextResponse.json(
        { error: '更新失败，请重试' },
        { status: 500 }
      );
    }

    return NextResponse.json({
      message: '更新成功',
      customer: {
        id: customer.id,
        name: customer.name,
        phone: customer.phone,
        email: customer.email,
        company: customer.company,
        created_at: customer.created_at,
      },
    });

  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
