import express from "express";
import type { Express } from "express";
import Stripe from "stripe";
import { handleSquarePaymentWebhook } from "../routers/payment.ts";
import { creditWallet, writeAuditLog } from "../db.ts";
import { notifyOwner } from "./notification.ts";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "", {
  apiVersion: "2026-02-25.clover" as any,
});

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET || "";

export function registerStripeWebhook(app: Express) {
  // CRITICAL: Register raw body parser BEFORE express.json()
  // This must be done in the main server file, but we provide the handler here
  
  app.post("/api/stripe/webhook", express.raw({ type: "application/json" }) as any, async (req, res) => {
    const sig = req.headers["stripe-signature"] as string;
    
    // Handle test events for webhook verification
    if (req.body && typeof req.body === "string") {
      try {
        const event = JSON.parse(req.body);
        if (event.id && event.id.startsWith("evt_test_")) {
          console.log("[Webhook] Test event detected, returning verification response");
          return res.json({ verified: true });
        }
      } catch (e) {
        // Continue with signature verification
      }
    }

    if (!sig || !webhookSecret) {
      console.error("[Webhook] Missing signature or webhook secret");
      return res.status(400).json({ verified: false, error: "Missing signature" });
    }

    let event: Stripe.Event;
    try {
      event = stripe.webhooks.constructEvent(
        req.body as Buffer,
        sig,
        webhookSecret
      );
    } catch (err: any) {
      console.error("[Webhook] Signature verification failed:", err.message);
      return res.status(400).json({ verified: false, error: "Signature verification failed" });
    }

    // Always return 200 OK with valid JSON
    try {
      console.log(`[Webhook] Processing event: ${event.type} (${event.id})`);
      
      // Process events asynchronously
      handleWebhookEvent(event).catch(err => {
        console.error("[Webhook] Error processing event:", err);
      });
      
      // Log webhook event for debugging
      console.log(`[Webhook] Event processed: ${event.type}`);

      // Return success immediately
      return res.json({ verified: true });
    } catch (err: any) {
      console.error("[Webhook] Error:", err.message);
      // Still return 200 OK to acknowledge receipt
      return res.json({ verified: true });
    }
  });
}

async function handleWebhookEvent(event: Stripe.Event) {
  try {
    // Use the payment router's webhook handler
    await handleSquarePaymentWebhook(event);
  } catch (err: any) {
    console.error("[Webhook] Error processing payment event:", err.message);
  }
}
