// Clerk → Supabase user sync webhook.
//
// Subscribes to `user.created` and `user.updated` events. On each, upserts
// the Clerk user into the `users` table so server-side code can join
// against it without re-calling Clerk's API.
//
// Set CLERK_WEBHOOK_SECRET in .env.local. Configure the webhook endpoint
// in https://dashboard.clerk.com → Webhooks → Add Endpoint:
//   URL: https://<your-domain>/api/webhooks/clerk
//   Events: user.created, user.updated, user.deleted

import { Webhook } from 'svix';
import { headers } from 'next/headers';
import { NextResponse } from 'next/server';
import { getServiceSupabase } from '@/lib/db';

export async function POST(req: Request) {
  const secret = process.env.CLERK_WEBHOOK_SECRET;
  if (!secret) {
    return NextResponse.json({ error: 'webhook_secret_missing' }, { status: 500 });
  }

  const payload = await req.text();
  const hdrs = await headers();
  const svixId = hdrs.get('svix-id');
  const svixTimestamp = hdrs.get('svix-timestamp');
  const svixSignature = hdrs.get('svix-signature');
  if (!svixId || !svixTimestamp || !svixSignature) {
    return NextResponse.json({ error: 'svix_headers_missing' }, { status: 400 });
  }

  let evt: { type: string; data: Record<string, unknown> };
  try {
    evt = new Webhook(secret).verify(payload, {
      'svix-id': svixId,
      'svix-timestamp': svixTimestamp,
      'svix-signature': svixSignature,
    }) as { type: string; data: Record<string, unknown> };
  } catch (err) {
    return NextResponse.json({ error: 'signature_invalid', detail: err instanceof Error ? err.message : String(err) }, { status: 400 });
  }

  const supabase = getServiceSupabase();

  if (evt.type === 'user.created' || evt.type === 'user.updated') {
    const d = evt.data as { id: string; email_addresses?: Array<{ email_address: string }>; first_name?: string; last_name?: string };
    const email = d.email_addresses?.[0]?.email_address;
    await supabase.from('users').upsert({
      clerk_id: d.id,
      email,
      first_name: d.first_name ?? null,
      last_name: d.last_name ?? null,
    }, { onConflict: 'clerk_id' });
  } else if (evt.type === 'user.deleted') {
    const d = evt.data as { id: string };
    await supabase.from('users').delete().eq('clerk_id', d.id);
  }

  return NextResponse.json({ ok: true });
}
