import { db } from '@/lib/db';
import { verifyMidtransSignature } from '@/lib/payments';
import { jsonError } from '@/lib/http';
export async function POST(req: Request) {
  let body: any; try { body = await req.json(); } catch { return jsonError('Invalid JSON.'); }
  if (!verifyMidtransSignature(body)) return jsonError('Invalid payment signature.', 401);
  const orderId = String(body.order_id); const status = String(body.transaction_status ?? '');
  const eventKey = `midtrans:${orderId}:${status}:${String(body.transaction_id ?? '')}`;
  try {
    await db.$transaction(async tx => {
      await tx.webhookEvent.create({ data: { provider: 'midtrans', eventKey, payload: body } });
      const donation = await tx.donation.findUnique({ where: { orderId }, include: { streamer: true } });
      if (!donation) throw new Error('Unknown order');
      if (donation.status === 'PAID') return;
      if (status === 'settlement' || (status === 'capture' && body.fraud_status === 'accept')) {
        await tx.donation.update({ where: { id: donation.id }, data: { status: 'PAID', paidAt: new Date(), providerTransactionId: String(body.transaction_id ?? '') , paymentType: String(body.payment_type ?? '') } });
        const fee = Math.floor(donation.amount * 0.05); const net = donation.amount - fee;
        await tx.ledger.createMany({ data: [
          { userId: donation.streamerId, donationId: donation.id, type: 'DONATION_GROSS', amount: donation.amount, reference: `${orderId}:gross` },
          { userId: donation.streamerId, donationId: donation.id, type: 'PLATFORM_FEE', amount: -fee, reference: `${orderId}:fee` },
          { userId: donation.streamerId, donationId: donation.id, type: 'STREAMER_NET', amount: net, reference: `${orderId}:net` }
        ] });
      } else if (['deny','cancel','expire','failure'].includes(status)) await tx.donation.update({ where: { id: donation.id }, data: { status: status === 'expire' ? 'EXPIRED' : 'FAILED', providerTransactionId: String(body.transaction_id ?? '') } });
    });
  } catch (e) {
    // Duplicate webhook event means it was already processed successfully.
    if (e instanceof Error && 'code' in e && (e as any).code === 'P2002') return Response.json({ ok: true, duplicate: true });
    return jsonError('Webhook could not be processed.', 500);
  }
  return Response.json({ ok: true });
}
