// pages/api/policies/index.js
import prisma from "@/lib/prisma";

function assertAuth(req, res) {
  const secret = process.env.NEXT_PUBLIC_SECRET_TOKEN;
  const header = req.headers.authorization || "";
  if (!secret || header !== `Bearer ${secret}`) {
    res.status(401).json({ success: false, message: "Unauthorized" });
    return false;
  }
  return true;
}

function toISO(d) {
  if (!d) return null;
  const dt = d instanceof Date ? d : new Date(d);
  return Number.isNaN(dt.getTime()) ? null : dt.toISOString();
}

function decToString(v) {
  if (v === null || v === undefined) return null;
  // Prisma Decimal has toString()
  return typeof v?.toString === "function" ? v.toString() : String(v);
}

function serializePolicy(p) {
  return {
    id: p.id,
    agency: p.agency,
    startdate: toISO(p.startdate),
    enddate: toISO(p.enddate),
    insured: p.insured,
    policyEndorsementNo: p.policyEndorsementNo,
    product: p.product,
    plate: p.plate,
    premium: decToString(p.premium),
    assignments: p.assignments,
    paymentStatus: p.paymentStatus,

    grossPremium: decToString(p.grossPremium),
    paidAmount: decToString(p.paidAmount),
    vGecen: decToString(p.vGecen),
    remainingAmount: decToString(p.remainingAmount),

    netPremium: decToString(p.netPremium),
    commission: decToString(p.commission),
    branch: p.branch,
    representative: p.representative,
    policyStatus: p.policyStatus,
    renewed: p.renewed,

    brand: p.brand,
    brandType: p.brandType,
    modelYear: p.modelYear,
    motorNo: p.motorNo,
    chassisNo: p.chassisNo,
    vehicleValue: p.vehicleValue,
    usageType: p.usageType,
    licenseSerialNo: p.licenseSerialNo,
    inspectionDate: toISO(p.inspectionDate),
    productCode: p.productCode,
    phone: p.phone,
    nationalId: p.nationalId,
    birthDate: toISO(p.birthDate),

    createdAt: toISO(p.createdAt),
    updatedAt: toISO(p.updatedAt),
  };
}

export default async function handler(req, res) {
  if (!assertAuth(req, res)) return;

  if (req.method !== "GET") {
    return res.status(405).json({ success: false, message: "Method Not Allowed" });
  }

  try {
    const q = String(req.query.q || "").trim();
    const from = String(req.query.from || "").trim(); // YYYY-MM-DD
    const to = String(req.query.to || "").trim();     // YYYY-MM-DD
    const take = Math.min(Number(req.query.take || 500), 2000);

    const where = {};

    // date range on startdate
    if (from) {
      const fromDt = new Date(`${from}T00:00:00.000Z`);
      if (!Number.isNaN(fromDt.getTime())) {
        where.startdate = { ...(where.startdate || {}), gte: fromDt };
      }
    }
    if (to) {
      const toDt = new Date(`${to}T23:59:59.999Z`);
      if (!Number.isNaN(toDt.getTime())) {
        where.startdate = { ...(where.startdate || {}), lte: toDt };
      }
    }

    if (q) {
      where.OR = [
        { insured: { contains: q, mode: "insensitive" } },
        { plate: { contains: q, mode: "insensitive" } },
        { policyEndorsementNo: { contains: q, mode: "insensitive" } },
        { agency: { contains: q, mode: "insensitive" } },
      ];
    }

    const policies = await prisma.policy.findMany({
      where,
      orderBy: { startdate: "desc" },
      take,
    });

    return res.status(200).json({
      success: true,
      policies: policies.map(serializePolicy),
    });
  } catch (err) {
    console.error(err);
    return res.status(500).json({ success: false, message: "Server Error" });
  }
}