import type { AgentDetail, AgentRow } from '../views/agent-form';
import type { AgentSubAgentRow } from '../views/agent/agent-sub-agent-form';
import api from '../api';

export type AgentCreditSnapshot = {
  username: string;
  level?: number;
  creditLimit: string;
  usedCredit: string;
  availableCredit: string;
  directPlayerLiability?: string;
  childAgentExposure?: string;
};

export type AgentCreditAdjustContext = {
  target: AgentCreditSnapshot;
  parent?: AgentCreditSnapshot;
};

function dec(value: string | number | null | undefined): number {
  const n = Number(value ?? 0);
  return Number.isFinite(n) ? n : 0;
}

export function snapshotFromAgentRow(
  row: Pick<
    AgentRow | AgentDetail | AgentSubAgentRow,
    'username' | 'creditLimit' | 'usedCredit' | 'availableCredit'
  > & {
    level?: number;
    directPlayerLiability?: string;
    childAgentExposure?: string;
  },
): AgentCreditSnapshot {
  return {
    username: row.username,
    level: row.level,
    creditLimit: String(row.creditLimit),
    usedCredit: String(row.usedCredit),
    availableCredit: String(row.availableCredit),
    directPlayerLiability: row.directPlayerLiability,
    childAgentExposure: row.childAgentExposure,
  };
}

export async function fetchAdminAgentCreditContext(userId: string): Promise<AgentCreditAdjustContext> {
  const { data } = await api.get(`/admin/agents/${userId}`);
  const detail = data.data as AgentDetail;
  const target = snapshotFromAgentRow(detail);
  if (!detail.parentAgentId) {
    return { target };
  }
  const { data: parentRes } = await api.get(`/admin/agents/${detail.parentAgentId}`);
  const parentDetail = parentRes.data as AgentDetail;
  return {
    target,
    parent: snapshotFromAgentRow(parentDetail),
  };
}

/** 下级代理增信时，正数调整量上限约等于上级可用授信（与后端 exposure 校验一致） */
export function maxCreditIncreaseAmount(ctx: AgentCreditAdjustContext | null): number | undefined {
  if (!ctx?.parent) return undefined;
  return Math.max(0, dec(ctx.parent.availableCredit));
}

export function projectedCreditLimit(ctx: AgentCreditAdjustContext | null, adjustAmount: number): string | null {
  if (!ctx || !Number.isFinite(adjustAmount)) return null;
  const after = dec(ctx.target.creditLimit) + adjustAmount;
  if (after < 0) return null;
  return String(after);
}
