export type SettlementPeriodView = "bills" | "operations" | "ledger";

const VALID_VIEWS: SettlementPeriodView[] = ["bills", "operations", "ledger"];

function parsePositiveInt(raw: string | null): number | null {
  if (raw === null || raw === "") {
    return null;
  }
  const value = Number(raw);
  return Number.isInteger(value) && value > 0 ? value : null;
}

export function settlementCenterListHref(adminSiteId?: number | null): string {
  if (adminSiteId != null && adminSiteId > 0) {
    return `/admin/settlement-center?site=${adminSiteId}`;
  }
  return "/admin/settlement-center";
}

export function settlementPeriodViewHref(
  periodId: number,
  view: SettlementPeriodView = "bills",
  adminSiteId?: number | null,
): string {
  const params = new URLSearchParams({
    period: String(periodId),
    view,
  });
  if (adminSiteId != null && adminSiteId > 0) {
    params.set("site", String(adminSiteId));
  }
  return `/admin/settlement-center?${params.toString()}`;
}

export function parseSettlementCenterView(
  siteRaw: string | null,
  periodRaw: string | null,
  viewRaw: string | null,
): { siteId: number | null; periodId: number | null; view: SettlementPeriodView } {
  const normalizedView = viewRaw === "reports" ? "bills" : viewRaw;
  const view =
    normalizedView !== null && VALID_VIEWS.includes(normalizedView as SettlementPeriodView)
      ? (normalizedView as SettlementPeriodView)
      : "bills";

  return {
    siteId: parsePositiveInt(siteRaw),
    periodId: parsePositiveInt(periodRaw),
    view,
  };
}

export function isSettlementPeriodView(value: string): value is SettlementPeriodView {
  return VALID_VIEWS.includes(value as SettlementPeriodView);
}
