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

// GET /api/auth/me - 获取当前登录用户信息
export async function GET() {
  try {
    const cookieStore = await cookies();
    const customerId = cookieStore.get('customer_id')?.value;
    
    if (!customerId) {
      return NextResponse.json(
        { authenticated: false, customer: null },
        { status: 200 }
      );
    }
    
    const client = getSupabaseClient();
    
    const { data: customer, error } = await client
      .from('customers')
      .select('id, name, phone, email, company, created_at, updated_at')
      .eq('id', customerId)
      .single();
    
    if (error || !customer) {
      // Cookie 无效，清除它
      cookieStore.delete('customer_id');
      cookieStore.delete('customer_phone');
      return NextResponse.json(
        { authenticated: false, customer: null },
        { status: 200 }
      );
    }
    
    return NextResponse.json({ 
      authenticated: true, 
      customer
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json(
      { error: '服务器错误' },
      { status: 500 }
    );
  }
}
