import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { verifyPolarWebhook, handleSubscriptionEvent, handleOrderCreated } from '$lib/server/polar';

/**
 * POST /api/webhooks/polar
 *
 * Receives Polar subscription lifecycle events and syncs user roles in PocketBase.
 * Signature is verified via HMAC-SHA256 before any processing.
 *
 * Handled events:
 *   subscription.created  — new subscription (status may be "active" or "trialing")
 *   subscription.active   — subscription became active (e.g. after payment)
 *   subscription.updated  — catch-all: cancellations, renewals, plan changes
 *   subscription.canceled — cancel_at_period_end=true, still active until period end
 *   subscription.revoked  — access ended, downgrade to free
 *   order.created         — purchase / subscription_create: fast-path upgrade
 */
export const POST: RequestHandler = async ({ request }) => {
	const rawBody = await request.text();
	const signature = request.headers.get('webhook-signature') ?? '';

	if (!verifyPolarWebhook(rawBody, signature)) {
		log.warn('polar', 'webhook signature verification failed');
		return new Response('Unauthorized', { status: 401 });
	}

	let event: { type: string; data: Record<string, unknown> };
	try {
		event = JSON.parse(rawBody);
	} catch {
		return new Response('Bad Request', { status: 400 });
	}

	const { type, data } = event;
	log.info('polar', 'webhook received', { type });

	try {
		switch (type) {
			case 'subscription.created':
			case 'subscription.active':
			case 'subscription.updated':
			case 'subscription.canceled':
			case 'subscription.revoked':
				await handleSubscriptionEvent(type, data as unknown as Parameters<typeof handleSubscriptionEvent>[1]);
				break;

			case 'order.created':
				await handleOrderCreated(data as unknown as Parameters<typeof handleOrderCreated>[0]);
				break;

			default:
				log.debug('polar', 'unhandled webhook event type', { type });
		}
	} catch (err) {
		// Log but return 200 — Polar retries on non-2xx, we don't want retry storms
		log.error('polar', 'webhook handler error', { type, err: String(err) });
	}

	return new Response('OK', { status: 200 });
};
