import { apiClient } from '@/lib/api/client';
import type {
  SystemAccount,
  SystemAccountsResponse,
  SystemAccountsSummary,
} from '@/types/system-account';

export interface SystemMiningRecord {
  id: string;
  accountType: string;
  miningMinute: string;
  contributionRatio: string;
  totalContribution: string;
  secondDistribution: string;
  minedAmount: string;
  createdAt: string;
}

export interface SystemMiningRecordsResponse {
  records: SystemMiningRecord[];
  total: number;
  page: number;
  pageSize: number;
}

export interface SystemTransaction {
  id: string;
  accountType: string;
  type: string;
  amount: string;
  balanceBefore: string;
  balanceAfter: string;
  referenceId?: string;
  referenceType?: string;
  memo?: string;
  createdAt: string;
}

export interface SystemTransactionsResponse {
  transactions: SystemTransaction[];
  total: number;
  page: number;
  pageSize: number;
}

export const systemAccountsApi = {
  /**
   * Get all system accounts (merged local + synced data)
   */
  getList: async (): Promise<SystemAccountsResponse> => {
    const response = await apiClient.get('/system-accounts');
    return response.data.data;
  },

  /**
   * Get system accounts summary with mining config and circulation pool
   */
  getSummary: async (): Promise<SystemAccountsSummary> => {
    const response = await apiClient.get('/system-accounts/summary');
    return response.data.data;
  },

  /**
   * Get system account mining records
   */
  getMiningRecords: async (
    accountType: string,
    page: number = 1,
    pageSize: number = 20
  ): Promise<SystemMiningRecordsResponse> => {
    const response = await apiClient.get(
      `/system-accounts/${accountType}/records`,
      { params: { page, pageSize } }
    );
    return response.data.data;
  },

  /**
   * Get system account transactions
   */
  getTransactions: async (
    accountType: string,
    page: number = 1,
    pageSize: number = 20
  ): Promise<SystemTransactionsResponse> => {
    const response = await apiClient.get(
      `/system-accounts/${accountType}/transactions`,
      { params: { page, pageSize } }
    );
    return response.data.data;
  },
};

// Helper to categorize accounts for display
export function categorizeAccounts(accounts: SystemAccount[]) {
  // 核心系统账户类型（HQ、运营、手续费）
  const coreAccounts = ['HEADQUARTERS', 'OPERATION', 'FEE'];
  // 区域账户类型（省、市）
  const regionAccounts = ['PROVINCE', 'CITY'];

  return {
    mainPools: [] as SystemAccount[], // 池账户现在从 poolAccounts API 获取
    systemAccounts: accounts.filter((a) => coreAccounts.includes(a.accountType)),
    fixedAccounts: accounts.filter((a) => regionAccounts.includes(a.accountType)),
    otherAccounts: accounts.filter(
      (a) =>
        !coreAccounts.includes(a.accountType) &&
        !regionAccounts.includes(a.accountType)
    ),
  };
}
