import { NextResponse } from 'next/server';
import { db } from "@/drizzle/db";
import { tenants, saasPackages } from "@/drizzle/schema";
import { eq } from 'drizzle-orm';
import { cookies } from 'next/headers';
import jwt from 'jsonwebtoken';
import { XenditEngine } from "@/lib/xendit-engine";

export async function POST(req: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('jumpa_token')?.value;

    if (!token) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    const decoded = jwt.verify(token, process.env.JWT_SECRET as string) as { email: string; tenantId: string };

    const { packageId } = await req.json();
    if (!packageId) return NextResponse.json({ error: 'Missing Package ID' }, { status: 400 });

    // 1. Ambil data paket & tenant
    const [pkg] = await db.select().from(saasPackages).where(eq(saasPackages.id, packageId)).limit(1);
    const [tenant] = await db.select().from(tenants).where(eq(tenants.id, decoded.tenantId)).limit(1);

    if (!pkg || !tenant) return NextResponse.json({ error: 'Data not found' }, { status: 404 });

    // 2. Kalkulasi Harga (Hapus 'Rp. ' dan titik untuk nominal integer)
    const amount = parseInt(pkg.price.replace(/[^0-9]/g, ''));
    if (isNaN(amount) || amount === 0) {
       // Paket Gratis / Rp. 0
       return NextResponse.json({ error: 'Package price is 0. No payment needed.' }, { status: 400 });
    }

    // 3. Buat Invoice Xendit
    const externalId = `INV-${tenant.id.substring(0, 8)}-${Date.now()}`;
    const invoice = await XenditEngine.createInvoice({
      external_id: externalId,
      amount: amount,
      payer_email: decoded.email,
      description: `Subscription Upgrade: ${pkg.name} for ${tenant.name}`,
      success_redirect_url: `${req.headers.get('origin')}/id/admin?payment=success&id=${externalId}`,
      failure_redirect_url: `${req.headers.get('origin')}/id/admin?payment=failed`,
      currency: "IDR",
      items: [{
        name: pkg.name,
        quantity: 1,
        price: amount,
        category: "Subscription"
      }]
    });

    // 4. Log transaksi (Optional: Bisa simpan ke tabel transactions)
    console.log(`[CHECKOUT] Invoice created for ${tenant.name}: ${invoice.invoice_url}`);

    return NextResponse.json({ url: invoice.invoice_url });

  } catch (error) {
    const message = error instanceof Error ? error.message : "Internal Checkout Error";
    console.error("Checkout Error:", error);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
