import { redirect, error, type RequestHandler } from '@sveltejs/kit';
import prisma from '$lib/server/prisma';

export const GET: RequestHandler = async ({ url, locals }) => {
  const ref = url.searchParams.get('ref');
  if (!ref) throw error(400, 'Missing ref');

  if (!locals.user) throw error(401, 'Not authenticated');

  const payment = await prisma.payment.findFirst({ where: { providerRef: ref } });
  if (!payment) throw error(404, 'Payment not found');

  if (payment.userId !== locals.user.id) throw error(403, 'Forbidden');

  // if already succeeded, proceed to purchases
  if (payment.status === 'SUCCEEDED') {
    throw redirect(303, '/product?payment=success');
  }

  // prepare merged payload marker and mark payment succeeded
  const mergedPayload = {
    ...(payment.rawPayload as Record<string, any> || {}),
    confirmedBy: 'redirect'
  };

  await prisma.payment.update({
    where: { id: payment.id },
    data: {
      status: 'SUCCEEDED',
      rawPayload: mergedPayload
    }
  });

  const rp: any = mergedPayload || {};

  // try to capture a product id to redirect back to after processing
  let redirectProductId: number | null = null;
  if (rp.productId) {
    const pid = Number(rp.productId);
    if (Number.isFinite(pid) && pid > 0) redirectProductId = pid;
  }

  if (rp.type === 'DOCUMENT_PURCHASE' && rp.documentId) {
    try {
      const productDocumentId = Number(rp.documentId);
      if (!Number.isFinite(productDocumentId) || productDocumentId <= 0) {
        console.error('entitlement skipped (confirm): invalid productDocument id', rp.documentId);
      } else {
        const pd = await prisma.productDocument.findUnique({ where: { id: productDocumentId } });
        if (!pd) {
          console.error('entitlement skipped (confirm): productDocument not found', productDocumentId);
        } else {
          // capture product id from productDocument for redirect if present
          if (!redirectProductId && (pd as any).productId) {
            const pfromPd = Number((pd as any).productId);
            if (Number.isFinite(pfromPd) && pfromPd > 0) redirectProductId = pfromPd;
          }

          // find or create secure Document
          let secureDoc: any = null;
          if (pd.documentId) {
            secureDoc = await prisma.document.findUnique({ where: { id: pd.documentId } });
          }
          if (!secureDoc) {
            secureDoc = await prisma.document.create({
              data: {
                title: pd.originalName || `productdoc-${pd.id}`,
                pageCount: pd.pageCount ?? 0,
                wrappedKey: `auto-created-${Date.now()}`
              }
            });
            try {
              await prisma.productDocument.update({ where: { id: pd.id }, data: { documentId: secureDoc.id } });
            } catch (updErr: any) {
              console.error('failed to link productDocument -> document (confirm):', updErr?.message || updErr);
            }
          }

          // create entitlement idempotently
          try {
            await prisma.entitlement.create({
              data: {
                userId: payment.userId,
                documentId: secureDoc.id
              }
            });
          } catch (entErr: any) {
            console.error('entitlement create error (confirm):', entErr?.message || entErr);
          }

          // ensure an Order exists for this payment (idempotent)
          try {
            const existingOrder = await prisma.order.findFirst({ where: { billRefNumber: payment.providerRef ?? undefined } });
            if (!existingOrder) {
              const productId = (pd as any).productId ?? (rp.productId ? Number(rp.productId) : null);
              const total = Number(payment.amount ?? 0);
              const order = await prisma.order.create({
                data: {
                  userId: payment.userId,
                  totalPrice: total,
                  status: 'COMPLETED',
                  billRefNumber: payment.providerRef || String(payment.id),
                  description: `Document purchase ${productDocumentId}`,
                  ProductOnOrder: productId
                    ? {
                        create: [
                          {
                            productId,
                            quantity: 1,
                            unitPrice: total
                          }
                        ]
                      }
                    : undefined
                }
              });

              try {
                await prisma.payment.update({ where: { id: payment.id }, data: { orderId: order.id } });
              } catch (updErr: any) {
                console.error('failed to link payment -> order (confirm):', updErr?.message || updErr);
              }
            }
          } catch (ordErr: any) {
            console.error('order create error (confirm):', ordErr?.message || ordErr);
          }
        }
      }
    } catch (err: any) {
      console.error('entitlement/create error (confirm):', err?.message || err);
      // continue to redirect even if entitlement creation fails
    }
  }

  // after processing, redirect user to the purchased product page when possible
  if (redirectProductId) {
    throw redirect(303, `/product/${redirectProductId}?payment=success`);
  }

  // fallback to products listing
  throw redirect(303, '/product?payment=success');
};