import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/client';
import {
  sendProfileApprovedEmail,
  sendProfileRejectedEmail,
} from '@/lib/marketplace/emailService';

export async function POST(req: NextRequest) {
  try {
    const { profileId, action, reason } = await req.json();

    if (!profileId || !action) {
      return NextResponse.json({ error: 'profileId and action required' }, { status: 400 });
    }

    const supabase = createClient();

    // Fetch profile
    const { data: profile } = await supabase
      .from('marketplace_profiles')
      .select('*')
      .eq('id', profileId)
      .maybeSingle();

    if (!profile) {
      return NextResponse.json({ error: 'Profile not found' }, { status: 404 });
    }

    let email: string | null = null;
    let name = 'there';

    if (profile.profile_type === 'crew') {
      const { data: details } = await supabase
        .from('marketplace_crew_details')
        .select('name')
        .eq('profile_id', profileId)
        .maybeSingle();
      if (details?.name) name = details.name;
    } else {
      const { data: details } = await supabase
        .from('marketplace_vendor_details')
        .select('company_name, contact_email')
        .eq('profile_id', profileId)
        .maybeSingle();
      if (details?.company_name) name = details.company_name;
      if (details?.contact_email) email = details.contact_email;
    }

    if (email) {
      if (action === 'approve') {
        await sendProfileApprovedEmail(email, name);
      } else if (action === 'reject' && reason) {
        await sendProfileRejectedEmail(email, name, reason);
      }
    }

    return NextResponse.json({ success: true });
  } catch (err: any) {
    console.error('Admin notify error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
