import { customers } from "../customers/customers.mock";
import { bookings } from "../bookings/bookings.mock";

export type InvoiceStatus =
  | "Draft"
  | "Sent"
  | "Paid"
  | "Overdue"
  | "Cancelled";

export type Currency = "USD" | "ETB" | "DJF";

export interface Invoice {
  id: number;
  number: string;
  customerId: number;
  customer: string;
  bookingReference: string;
  amount: number;
  currency: Currency;
  status: InvoiceStatus;
  issueDate: string;
  dueDate: string;
  paidDate: string | null;
  notes: string;
}

const statuses: InvoiceStatus[] = [
  "Draft",
  "Sent",
  "Paid",
  "Overdue",
  "Cancelled",
];
const currencies: Currency[] = ["USD", "ETB", "DJF"];

export const invoices: Invoice[] = Array.from({ length: 24 }, (_, i) => {
  const customer = customers[i % customers.length] as (typeof customers)[number];
  const booking = bookings[i % bookings.length] as (typeof bookings)[number];
  const id = i + 1;
  const issue = new Date(2026, 3, 1 + (i % 28));
  const due = new Date(issue);
  due.setDate(due.getDate() + 30);
  const status = statuses[i % statuses.length] as InvoiceStatus;
  const currency = currencies[i % currencies.length] as Currency;
  const baseAmount = 5000 + (i * 1234) % 25000;
  return {
    id,
    number: `INV-2026-${String(id).padStart(4, "0")}`,
    customerId: customer.id,
    customer: customer.company,
    bookingReference: booking.reference,
    amount: Math.round(baseAmount * 100) / 100,
    currency,
    status,
    issueDate: issue.toISOString().slice(0, 10),
    dueDate: due.toISOString().slice(0, 10),
    paidDate:
      status === "Paid"
        ? new Date(due.getTime() - 86400000 * (i % 7))
            .toISOString()
            .slice(0, 10)
        : null,
    notes:
      i % 3 === 0
        ? "Net 30 payment terms."
        : i % 3 === 1
        ? "Bank transfer preferred."
        : "Payment due upon receipt.",
  };
});

export function getInvoiceById(id: number | string): Invoice | undefined {
  const numericId = typeof id === "string" ? Number(id) : id;
  return invoices.find((inv) => inv.id === numericId);
}

export function formatCurrency(amount: number, currency: Currency): string {
  const symbols: Record<Currency, string> = {
    USD: "$",
    ETB: "Br",
    DJF: "DJF",
  };
  return `${symbols[currency]} ${amount.toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
}
