import type { SettlementBillRow } from "@/api/admin-agent-settlement";

type BoundAgentRef = { id: number } | null | undefined;

function billPayeeParty(
  bill: Pick<SettlementBillRow, "owner_type" | "owner_id" | "counterparty_type" | "counterparty_id" | "net_amount">,
): { type: string; id: number } {
  if ((bill.net_amount ?? 0) < 0) {
    return { type: bill.owner_type, id: bill.owner_id };
  }

  return { type: bill.counterparty_type, id: bill.counterparty_id };
}

function agentBillOnDirectEdge(
  actorId: number,
  bill: Pick<SettlementBillRow, "owner_type" | "owner_id" | "counterparty_type" | "counterparty_id">,
): boolean {
  if (bill.owner_id === actorId) {
    return true;
  }
  if (bill.counterparty_type === "agent" && bill.counterparty_id === actorId) {
    return true;
  }
  if (bill.counterparty_type === "platform" && bill.owner_id === actorId) {
    return true;
  }

  return false;
}

/** 绑定代理仅可操作直属边账单，且代理账单仅收款方可登记（与后端 AdminAgentSettlementScope 一致）。 */
export function settlementBillOperableByBoundAgent(
  bill: Pick<
    SettlementBillRow,
    "bill_type" | "owner_type" | "owner_id" | "counterparty_type" | "counterparty_id" | "net_amount"
  >,
  boundAgent: BoundAgentRef,
): boolean {
  if (boundAgent == null) {
    return true;
  }

  if (bill.owner_type === "player" || bill.bill_type === "player") {
    return bill.counterparty_type === "agent" && bill.counterparty_id === boundAgent.id;
  }

  if (bill.owner_type === "agent" || bill.bill_type === "agent") {
    if (!agentBillOnDirectEdge(boundAgent.id, bill)) {
      return false;
    }

    const payee = billPayeeParty(bill);

    return payee.type === "agent" && payee.id === boundAgent.id;
  }

  return false;
}
