import { Webhook } from 'standardwebhooks';

export const DODO_BASE = process.env.DODO_PAYMENTS_ENV === 'live' ? 'https://live.dodopayments.com' : 'https://test.dodopayments.com';
export const dodoConfigured = () => !!process.env.DODO_PAYMENTS_API_KEY;

export async function createCheckout(input: { productId: string; email: string; name: string; returnUrl: string; cancelUrl: string; metadata: Record<string, string> }) {
  const r = await fetch(`${DODO_BASE}/checkouts`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      product_cart: [{ product_id: input.productId, quantity: 1 }],
      customer: { email: input.email, name: input.name },
      billing_address: { country: 'TR' },
      return_url: input.returnUrl, cancel_url: input.cancelUrl,
      metadata: input.metadata,
      customization: { force_language: 'tr', theme: 'light' },
      feature_flags: { redirect_immediately: true },
    }),
  });
  if (!r.ok) throw new Error(`Dodo checkout ${r.status}: ${(await r.text()).slice(0, 300)}`);
  return (await r.json()) as { session_id: string; checkout_url: string };
}

/** Standard Webhooks imza doğrulaması (webhook-id, webhook-timestamp, webhook-signature). */
export function verifyDodoWebhook(raw: string, headers: Headers) {
  const secret = process.env.DODO_WEBHOOK_SECRET;
  if (!secret) throw new Error('DODO_WEBHOOK_SECRET tanımlı değil');
  const wh = new Webhook(secret);
  return wh.verify(raw, {
    'webhook-id': headers.get('webhook-id') || '',
    'webhook-timestamp': headers.get('webhook-timestamp') || '',
    'webhook-signature': headers.get('webhook-signature') || '',
  }) as { type: string; business_id?: string; timestamp?: string; data: Record<string, unknown> & { metadata?: Record<string, string>; payment_id?: string; total_amount?: number; currency?: string; checkout_session_id?: string } };
}
