import type { AgentRecord } from "@/types/master-data";

type SerializableAgent = {
  id: bigint;
  code: string;
  name: string;
  identityType: string;
  identityNumber: string;
  mobilePhone: string | null;
  email: string | null;
  address: string | null;
  notes: string | null;
  joinDate: Date;
  currentBalance: { toNumber(): number };
  capitalBalance: { toNumber(): number };
  createdAt: Date;
  updatedAt: Date;
  profitShareScheme: {
    id: bigint;
    code: string;
    name: string;
    shareAgent: { toNumber(): number };
    shareCompany: { toNumber(): number };
  };
  bankAccounts: Array<{
    id: bigint;
    accountNumber: string;
    bank: {
      id: bigint;
      code: string;
      name: string;
    };
  }>;
};

export function serializeAgent(agent: SerializableAgent): AgentRecord {
  return {
    id: agent.id.toString(),
    code: agent.code,
    name: agent.name,
    identity_type: agent.identityType as AgentRecord["identity_type"],
    identity_number: agent.identityNumber,
    mobile_phone: agent.mobilePhone,
    email: agent.email,
    address: agent.address,
    notes: agent.notes,
    join_date: agent.joinDate.toISOString().slice(0, 10),
    profit_share_scheme: {
      id: agent.profitShareScheme.id.toString(),
      code: agent.profitShareScheme.code,
      name: agent.profitShareScheme.name,
      share_agent: agent.profitShareScheme.shareAgent.toNumber(),
      share_company: agent.profitShareScheme.shareCompany.toNumber()
    },
    profit_share_balance: agent.currentBalance.toNumber(),
    capital_balance: agent.capitalBalance.toNumber(),
    bank_accounts: agent.bankAccounts.map((account) => ({
      id: account.id.toString(),
      bank_id: account.bank.id.toString(),
      bank_code: account.bank.code,
      bank_name: account.bank.name,
      account_number: account.accountNumber
    })),
    created_at: agent.createdAt.toISOString(),
    updated_at: agent.updatedAt.toISOString()
  };
}
