import { getSettlementBills, type SettlementBillRow } from "@/api/admin-agent-settlement";
import type { AdminPlayerRow } from "@/types/api/admin-player";

import {
  settlementPeriodViewHref,
  type SettlementBillScopeFilter,
} from "@/modules/settlement/settlement-center-nav";

export type SettlementBillFocus = "confirm" | "payment";

function pickActionableBill(bills: SettlementBillRow[]): SettlementBillRow | null {
  const pending = bills.find((bill) => bill.status === "pending_confirm");
  if (pending) {
    return pending;
  }

  const awaiting = bills.find(
    (bill) =>
      ["confirmed", "partial_paid", "overdue"].includes(bill.status) &&
      Number(bill.unpaid_amount ?? 0) > 0,
  );
  if (awaiting) {
    return awaiting;
  }

  return bills[0] ?? null;
}

export function settlementBillDeepLinkHref(
  bill: SettlementBillRow,
  adminSiteId?: number | null,
): string {
  const scope: SettlementBillScopeFilter =
    bill.status === "pending_confirm" ? "pending_confirm" : "awaiting_payment";
  const focus: SettlementBillFocus =
    bill.status === "pending_confirm" ? "confirm" : "payment";

  const params = new URLSearchParams(
    settlementPeriodViewHref(
      bill.settlement_period_id,
      "bills",
      adminSiteId ?? bill.admin_site_id,
      scope,
    ).split("?")[1] ?? "",
  );
  params.set("bill", String(bill.id));
  params.set("focus", focus);

  return `/admin/settlement-center?${params.toString()}`;
}

export async function resolvePlayerSettlementHref(
  player: Pick<AdminPlayerRow, "id" | "site_player_id" | "username">,
  adminSiteId?: number | null,
): Promise<string | null> {
  const keyword =
    player.site_player_id?.trim() || player.username?.trim() || String(player.id);

  const data = await getSettlementBills({
    bill_type: "player",
    keyword,
    per_page: 20,
    page: 1,
  });

  const items = (data.items ?? []).filter(
    (bill) =>
      bill.bill_type === "player" &&
      bill.owner_id === player.id &&
      (bill.status === "pending_confirm" || Number(bill.unpaid_amount ?? 0) > 0),
  );

  const bill = pickActionableBill(items);
  if (bill === null) {
    return null;
  }

  return settlementBillDeepLinkHref(bill, adminSiteId);
}