import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { NextRequest, NextResponse } from "next/server";
import type { POStatus } from "@prisma/client";

const PO_STATUS_LABELS: Record<string, string> = {
  DRAFT: "Draft", SUBMITTED: "Submitted", MGR_REVIEW: "Pending Approval",
  VENDOR_ID_PENDING: "Vendor ID Pending", EDITS_REQUESTED: "Edits Requested",
  REJECTED: "Rejected", MGR_APPROVED: "Approved", SENT_FOR_PAYMENT: "Sent for Payment",
  PAID_DELIVERED: "Paid / Delivered", CLOSED: "Closed", CANCELLED: "Cancelled",
};

export async function GET(request: NextRequest) {
  const session = await auth();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  if (!hasPermission(session.user.role, "export_reports")) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const sp = request.nextUrl.searchParams;
  const format = sp.get("format") ?? "csv";
  const dateFrom = sp.get("dateFrom");
  const dateTo = sp.get("dateTo");
  const approvedFrom = sp.get("approvedFrom");
  const approvedTo = sp.get("approvedTo");
  const vesselId = sp.get("vesselId");
  const statuses = sp.getAll("status").filter(Boolean);

  const where: NonNullable<Parameters<typeof db.purchaseOrder.findMany>[0]>["where"] = {};
  if (dateFrom || dateTo) {
    const createdAt: { gte?: Date; lt?: Date } = {};
    if (dateFrom) createdAt.gte = new Date(dateFrom);
    if (dateTo) {
      const end = new Date(dateTo);
      end.setDate(end.getDate() + 1);
      createdAt.lt = end;
    }
    where.createdAt = createdAt;
  }
  if (approvedFrom || approvedTo) {
    const approvedAt: { gte?: Date; lt?: Date } = {};
    if (approvedFrom) approvedAt.gte = new Date(approvedFrom);
    if (approvedTo) {
      const end = new Date(approvedTo);
      end.setDate(end.getDate() + 1);
      approvedAt.lt = end;
    }
    where.approvedAt = approvedAt;
  }
  if (vesselId) where.vesselId = vesselId;
  if (statuses.length > 0) where.status = { in: statuses as POStatus[] };

  const orders = await db.purchaseOrder.findMany({
    where,
    include: { submitter: true, vessel: true, account: true, vendor: true },
    orderBy: { createdAt: "desc" },
  });

  if (format === "pdf") {
    const rows = orders.map((po) => `
      <tr>
        <td>${po.poNumber}</td>
        <td>${po.title}</td>
        <td>${PO_STATUS_LABELS[po.status] ?? po.status}</td>
        <td>${po.vessel.name}</td>
        <td>${po.submitter.name}</td>
        <td>${po.vendor?.name ?? "—"}</td>
        <td style="text-align:right">${Number(po.totalAmount).toLocaleString("en-IN", { style: "currency", currency: "INR" })}</td>
        <td>${po.createdAt.toLocaleDateString("en-IN")}</td>
      </tr>`).join("");

    const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>PO Export — PPMS</title>
<style>
  body { font-family: Arial, sans-serif; font-size: 11px; margin: 20px; color: #111; }
  h1 { font-size: 16px; margin-bottom: 4px; }
  p { font-size: 10px; color: #555; margin-bottom: 12px; }
  table { width: 100%; border-collapse: collapse; }
  th { background: #f0f0f0; border: 1px solid #ccc; padding: 5px 8px; text-align: left; font-size: 10px; }
  td { border: 1px solid #ddd; padding: 4px 8px; vertical-align: top; }
  tr:nth-child(even) td { background: #fafafa; }
  .no-print { margin-bottom: 12px; }
  @media print { .no-print { display: none; } }
</style>
</head>
<body>
<div class="no-print">
  <button onclick="window.print()" style="padding:6px 16px;font-size:13px;cursor:pointer;">Print / Save as PDF</button>
</div>
<h1>Purchase Order Report — PPMS</h1>
<p>Generated: ${new Date().toLocaleString("en-IN")} · ${orders.length} orders</p>
<table>
  <thead>
    <tr>
      <th>PO Number</th><th>Title</th><th>Status</th><th>Cost Centre</th>
      <th>Submitter</th><th>Vendor</th><th style="text-align:right">Amount</th><th>Created</th>
    </tr>
  </thead>
  <tbody>${rows}</tbody>
</table>
<script>window.onload = function() { window.print(); };</script>
</body>
</html>`;

    return new NextResponse(html, {
      headers: { "Content-Type": "text/html; charset=utf-8" },
    });
  }

  // Default: CSV
  const headers = ["PO Number", "Title", "Status", "Cost Centre", "Account", "Vendor", "Submitter", "Amount", "Currency", "Created"];
  const csvRows = orders.map((po) => [
    po.poNumber,
    `"${po.title.replace(/"/g, '""')}"`,
    po.status,
    po.vessel.name,
    po.account.name,
    po.vendor?.name ?? "",
    po.submitter.name,
    po.totalAmount.toString(),
    po.currency,
    po.createdAt.toISOString(),
  ]);

  const csv = [headers.join(","), ...csvRows.map((r) => r.join(","))].join("\n");

  return new NextResponse(csv, {
    headers: {
      "Content-Type": "text/csv",
      "Content-Disposition": `attachment; filename="pelagia-po-export-${Date.now()}.csv"`,
    },
  });
}
