import { adminRequest } from "@/lib/admin-http";

const A = `/admin`;

export type SettlementPeriodSummary = {
  player_bills: number;
  agent_bills: number;
  adjustment_bills: number;
  pending_confirm: number;
  awaiting_payment: number;
  settled: number;
  total_unpaid: number;
  total_net?: number;
};

export type SettlementPeriodPipeline = {
  credit_ledger_count: number;
  share_ledger_count: number;
  game_win_loss_total?: number;
  win_loss_scope?: "platform" | "agent";
  basic_rebate_total?: number;
  unsettled_ticket_count?: number;
};

export type SettlementPeriodRow = {
  id: number;
  admin_site_id: number;
  period_start: string;
  period_end: string;
  status: string;
  summary?: SettlementPeriodSummary;
  pipeline?: SettlementPeriodPipeline;
};

export type AgentSettlementReportType =
  | "summary"
  | "player_win_loss"
  | "agent_share"
  | "rebate"
  | "credit"
  | "unpaid_bills"
  | "overdue"
  | "platform_pnl"
  | "draw_period";

export type DownlineShareItem = {
  owner_id: number;
  owner_label: string;
  share_profit: number;
};

export type DownlineShareBreakdown = {
  total: number;
  items: DownlineShareItem[];
};

export type SettlementBillRow = {
  id: number;
  settlement_period_id: number;
  bill_type: string;
  owner_type: string;
  owner_id: number;
  counterparty_type: string;
  counterparty_id: number;
  gross_win_loss?: number;
  rebate_amount?: number;
  platform_rounding_adjustment?: number;
  net_amount: number;
  unpaid_amount: number;
  paid_amount: number;
  status: string;
  owner_label?: string;
  counterparty_label?: string;
  player_username?: string | null;
  player_site_player_id?: string | null;
  player_id_display?: number | null;
  direct_agent_label?: string | null;
  superior_agent_label?: string | null;
  owner_party_label?: string | null;
  owner_funding_mode?: string | null;
  owner_auth_source?: string | null;
  period_start?: string;
  period_end?: string;
  admin_site_id?: number;
  meta_json?: string | Record<string, unknown> | null;
};

export async function getSettlementPeriods(params?: {
  admin_site_id?: number;
}): Promise<{ items: SettlementPeriodRow[] }> {
  return adminRequest.get(`${A}/settlement-periods`, { params });
}

export async function postSettlementPeriod(body: {
  admin_site_id: number;
  period_start: string;
  period_end: string;
}): Promise<SettlementPeriodRow> {
  return adminRequest.post(`${A}/settlement-periods`, body);
}

export type SettlementPeriodOpenHints = {
  suggested_start: string;
  suggested_end: string;
  occupied_period_dates: string[];
  pending_activity_dates: string[];
  unpaid_bill_dates: string[];
};

export async function getSettlementPeriodOpenHints(params: {
  admin_site_id: number;
}): Promise<SettlementPeriodOpenHints> {
  return adminRequest.get(`${A}/settlement-periods/open-hints`, { params });
}

export type SettlementPeriodCloseResult = {
  period_id: number;
  unsettled_ticket_count?: number;
  player_count?: number;
};

export async function postSettlementPeriodClose(
  periodId: number,
): Promise<SettlementPeriodCloseResult> {
  return adminRequest.post(`${A}/settlement-periods/${periodId}/close`);
}

export async function postSettlementBillBadDebtWriteOff(
  billId: number,
  body?: { reason?: string; idempotency_key?: string },
): Promise<{ original_bill_id: number; bad_debt_bill_id: number; bill: SettlementBillRow }> {
  return adminRequest.post(`${A}/settlement-bills/${billId}/bad-debt-write-off`, body ?? {});
}

export type SettlementBillListScope =
  | "pending_confirm"
  | "awaiting_payment"
  | "settled"
  | "adjustment";

export type SettlementCreditLedgerRow = {
  entry_kind: string;
  id: number;
  row_key: string;
  txn_no: string;
  player_id: number;
  site_code?: string | null;
  username?: string | null;
  nickname?: string | null;
  site_player_id?: string | null;
  biz_type: string;
  biz_no?: string | null;
  ref_type?: string | null;
  ref_id?: number | null;
  direction: 1 | 2;
  amount: number;
  amount_formatted?: string;
  signed_amount?: number;
  currency_code?: string;
  status: string;
  created_at?: string | null;
  ledger_source: string;
  funding_mode?: string | null;
  direct_agent_label?: string | null;
  parent_agent_label?: string | null;
  play_code?: string | null;
  draw_no?: string | null;
  ticket_item_id?: number | null;
  settlement_bill_id?: number | null;
  bill_status?: string | null;
};

export async function getCreditLedger(params: {
  admin_site_id: number;
  /** 0 或不传表示不限账期（玩家详情等场景） */
  settlement_period_id?: number;
  player_id?: number;
  entry_kind?: "credit";
  bet_flow_only?: boolean;
  bet_flow_display?: "simple";
  player_account?: string;
  reason?: string;
  page?: number;
  per_page?: number;
}): Promise<{
  items: SettlementCreditLedgerRow[];
  total: number;
  page: number;
  per_page: number;
  ledger_source: string;
  truncated?: boolean;
}> {
  return adminRequest.get(`${A}/credit-ledger`, { params });
}

export type SettlementOperationRow = {
  kind: "payment" | "adjustment" | "reversal" | "bad_debt";
  record_id: number;
  bill_id: number;
  amount: number;
  summary: string;
  detail: string | null;
  sort_at: string | null;
};

export async function getSettlementOperations(params: {
  admin_site_id: number;
  settlement_period_id: number;
  bill_id?: number;
  keyword?: string;
  operation_type?: "all" | "payment" | "adjustment" | "reversal" | "bad_debt";
  page?: number;
  per_page?: number;
}): Promise<{
  items: SettlementOperationRow[];
  total: number;
  page: number;
  per_page: number;
  last_page: number;
}> {
  return adminRequest.get(`${A}/settlement-operations`, { params });
}

export async function getSettlementBills(params?: {
  settlement_period_id?: number;
  admin_site_id?: number;
  bill_type?: string;
  scope?: SettlementBillListScope;
  bill_id?: number;
  keyword?: string;
  page?: number;
  per_page?: number;
}): Promise<{
  items: SettlementBillRow[];
  total?: number;
  page?: number;
  per_page?: number;
}> {
  return adminRequest.get(`${A}/settlement-bills`, { params });
}

export type SettlementPaymentRow = {
  id: number;
  settlement_bill_id: number;
  payer_type: string;
  payer_id: number;
  payee_type: string;
  payee_id: number;
  amount: number;
  method: string | null;
  proof?: string | null;
  remark?: string | null;
  status: string;
  bill_type: string;
  owner_type: string;
  owner_id: number;
  period_start?: string;
  period_end?: string;
  confirmed_at?: string | null;
  created_at?: string;
};

export type SettlementBillPaymentRow = {
  id: number;
  amount: number;
  status: string;
  method?: string | null;
  proof?: string | null;
  remark?: string | null;
};

export async function getSettlementPayments(params?: {
  settlement_period_id?: number;
  admin_site_id?: number;
  page?: number;
  per_page?: number;
}): Promise<{
  items: SettlementPaymentRow[];
  total: number;
  page: number;
  per_page: number;
  last_page: number;
}> {
  return adminRequest.get(`${A}/settlement-payments`, { params });
}

export type SettlementAdjustmentRow = {
  id: number;
  settlement_period_id: number | null;
  original_bill_id: number | null;
  adjustment_type: string;
  amount: number;
  reason: string | null;
  created_by: number | null;
  period_start?: string;
  period_end?: string;
  original_bill_type?: string | null;
  original_owner_type?: string | null;
  original_owner_id?: number | null;
  created_at?: string;
};

export async function getSettlementAdjustments(params?: {
  settlement_period_id?: number;
  admin_site_id?: number;
  adjustment_type?: string;
  page?: number;
  per_page?: number;
}): Promise<{
  items: SettlementAdjustmentRow[];
  total: number;
  page: number;
  per_page: number;
  last_page: number;
}> {
  return adminRequest.get(`${A}/settlement-adjustments`, { params });
}

export type RebateAllocationRow = {
  id: number;
  rebate_record_id: number;
  settlement_bill_id?: number;
  participant_type: string;
  participant_id: number;
  participant_label?: string;
  actual_share_rate: number;
  allocated_amount: number;
  allocation_rule: string;
};

export async function getSettlementBill(billId: number): Promise<{
  bill: SettlementBillRow;
  payments: SettlementBillPaymentRow[];
  rebate_allocations: RebateAllocationRow[];
  adjustments: Array<{ id: number; amount: number; adjustment_type: string; reason: string | null }>;
  tier_edge?: string | null;
  downline_shares?: DownlineShareBreakdown;
}> {
  return adminRequest.get(`${A}/settlement-bills/${billId}`);
}

export async function postSettlementBillConfirm(billId: number): Promise<{ bill_id: number; status: string }> {
  return adminRequest.post(`${A}/settlement-bills/${billId}/confirm`);
}

export async function postSettlementBillPayment(
  billId: number,
  body: { amount: number; method?: string; proof?: string; remark?: string; idempotency_key?: string },
): Promise<{ bill: SettlementBillRow }> {
  return adminRequest.post(`${A}/settlement-bills/${billId}/payments`, body);
}

export type AgentSettlementReportResponse = {
  type: string;
  settlement_period_id: number | null;
  period_start: string;
  period_end: string;
  data: unknown;
  footnote: string | null;
};

export async function getAgentSettlementReport(params: {
  type: AgentSettlementReportType;
  settlement_period_id?: number;
  admin_site_id?: number;
}): Promise<AgentSettlementReportResponse> {
  return adminRequest.get<AgentSettlementReportResponse>(`${A}/settlement-reports`, { params });
}

export async function postSettlementBillAdjustment(
  billId: number,
  body: { amount: number; adjustment_type?: "adjustment" | "reversal"; reason?: string; idempotency_key?: string },
): Promise<{ adjustment_bill_id: number; bill: SettlementBillRow }> {
  return adminRequest.post(`${A}/settlement-bills/${billId}/adjustments`, body);
}
