/** Phase 6: the company is paid by settlements (like a store, no branches). */
export type SettlementStatus = "DRAFT" | "TRANSFERRED";
export type SettlementCycle = "DAILY" | "WEEKLY" | "MONTHLY";

export const SETTLEMENT_STATUSES: SettlementStatus[] = ["DRAFT", "TRANSFERRED"];

export type PayoutAccount = {
  id: number;
  name: string;
  iban: string;
  phone?: string | null;
  ownerName?: string | null;
  isDefault?: boolean;
  Bank?: { nameAr?: string | null; nameEn?: string | null } | null;
};

export type SettlementSummary = {
  due: number | string;
  owed: number | string;
  net: number | string;
  held: number | string;
  paid: number | string;
  cycle: SettlementCycle;
  cycleIsCustom: boolean;
  payoutAccount: PayoutAccount | null;
};

export type Settlement = {
  id: number;
  cycle: SettlementCycle;
  periodStart: string;
  periodEnd: string;
  dueTotal: number | string;
  owedTotal: number | string;
  amount: number | string;
  ordersCount: number;
  status: SettlementStatus;
  bankName?: string | null;
  accountOwnerName?: string | null;
  accountIban?: string | null;
  accountPhone?: string | null;
  transferReference?: string | null;
  transferProofPath?: string | null;
  transferredAt?: string | null;
  createdAt: string;
};

export type SettlementEntry = {
  id: number;
  type: string;
  amount: number | string;
  orderId?: number | null;
  createdAt: string;
  reason?: string | null;
  reference?: string | null;
  Order?: {
    id: number;
    status?: string;
    paymentMethod?: string;
    deliveryStatus?: string;
    deliveredAt?: string | null;
  } | null;
};

/** Money fields come from Prisma Decimal as strings. */
export const money = (n: number | string | null | undefined) =>
  Number(n ?? 0).toFixed(2);

export const bankDisplayName = (
  b: { nameAr?: string | null; nameEn?: string | null } | null | undefined,
  locale: string,
) =>
  (locale.startsWith("ar") ? (b?.nameAr ?? b?.nameEn) : (b?.nameEn ?? b?.nameAr)) ?? "";
