import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import crypto from 'crypto';
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 { password, newEmail } = body;

    // 验证必填字段
    if (!password || !newEmail) {
      return NextResponse.json(
        { error: '请填写完整信息' },
        { status: 400 }
      );
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(newEmail)) {
      return NextResponse.json(
        { error: '邮箱格式不正确' },
        { status: 400 }
      );
    }

    // 获取用户信息
    const { data: customer, error: fetchError } = await supabase
      .from('customers')
      .select('password_hash')
      .eq('id', customerId)
      .single();

    if (fetchError || !customer) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 验证密码
    const passwordHash = crypto
      .createHash('sha256')
      .update(password)
      .digest('hex');

    if (passwordHash !== customer.password_hash) {
      return NextResponse.json(
        { error: '密码错误' },
        { status: 400 }
      );
    }

    // 检查邮箱是否已被其他用户使用
    const { data: existingCustomer } = await supabase
      .from('customers')
      .select('id')
      .eq('email', newEmail)
      .neq('id', customerId)
      .single();

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

    // 更新邮箱
    const { data: updatedCustomer, error: updateError } = await supabase
      .from('customers')
      .update({
        email: newEmail,
        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: updatedCustomer.id,
        name: updatedCustomer.name,
        phone: updatedCustomer.phone,
        email: updatedCustomer.email,
        company: updatedCustomer.company,
        created_at: updatedCustomer.created_at,
      },
    });

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