import { NextRequest, NextResponse } from "next/server";

/**
 * Email webhook handler
 * Receives delivery/open/click/bounce events from Resend
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { type, data } = body;

    console.log(`[Email Webhook] Event: ${type}`, data);

    switch (type) {
      case "email.delivered": {
        // In production:
        // await supabaseAdmin.from('outreach').update({
        //   status: 'delivered',
        //   delivered_at: new Date().toISOString(),
        // }).eq('external_id', data.email_id);
        console.log("[Email] Delivered to:", data?.to);
        break;
      }

      case "email.opened": {
        // In production:
        // await supabaseAdmin.from('outreach').update({
        //   status: 'opened',
        //   opened_at: new Date().toISOString(),
        // }).eq('external_id', data.email_id);
        //
        // Also update buyer engagement score:
        // Increment engagement_score by 5 for opens
        console.log("[Email] Opened by:", data?.to);
        break;
      }

      case "email.clicked": {
        // In production:
        // await supabaseAdmin.from('outreach').update({
        //   status: 'clicked',
        //   clicked_at: new Date().toISOString(),
        // }).eq('external_id', data.email_id);
        //
        // Increment engagement_score by 10 for clicks
        console.log("[Email] Clicked by:", data?.to);
        break;
      }

      case "email.bounced": {
        // In production:
        // await supabaseAdmin.from('outreach').update({
        //   status: 'bounced',
        // }).eq('external_id', data.email_id);
        //
        // Decrease engagement score, possibly mark buyer as unresponsive
        console.log("[Email] Bounced for:", data?.to);
        break;
      }

      case "email.complained": {
        // Mark as spam complaint, remove from future outreach
        console.log("[Email] Complaint from:", data?.to);
        break;
      }

      default:
        console.log(`[Email Webhook] Unhandled event: ${type}`);
    }

    return NextResponse.json({ received: true });
  } catch (error) {
    console.error("Email webhook error:", error);
    return NextResponse.json(
      { error: "Webhook processing failed" },
      { status: 500 }
    );
  }
}

export async function GET() {
  return NextResponse.json({
    status: "ok",
    message: "Email webhook endpoint active. POST events from Resend here.",
  });
}
