import api, { unwrap } from './request';

export interface AccountingCloseResp extends Record<string, unknown> {
  closeId: number;
  closePeriod: string;
  closeType: string;
  closeTypeName?: string;
  closeStatus: string;
  closeStatusName?: string;
  journalPrefix?: string;
  journalCount?: number;
  totalDebit?: number;
  totalCredit?: number;
  balanceDiff?: number;
  closedAt?: string;
  closedByName?: string;
  reopenedAt?: string;
  reopenedByName?: string;
  reopenReason?: string;
  createdAt?: string;
  updatedAt?: string;
}

export interface AccountBalanceSnapshot extends Record<string, unknown> {
  snapshotId: number;
  closeId: number;
  accountCode: string;
  accountName?: string;
  accountType?: string;
  debitTotal: number;
  creditTotal: number;
  balance: number;
  createdAt?: string;
}

export interface AccountingCloseSearchParam {
  closePeriod?: string;
  closeType?: string;
  closeStatus?: string;
  pageNum?: number;
  pageSize?: number;
}

export interface AccountingCloseDraftReq {
  closePeriod: string;
  closeType: string;
}

export const accountingCloseApi = {
  list: (params?: AccountingCloseSearchParam) =>
    unwrap<{ list: AccountingCloseResp[]; total: number }>(
      api.get('/api/accounting-closes', { params })
    ),
  detail: (id: number) =>
    unwrap<AccountingCloseResp>(api.get(`/api/accounting-closes/${id}`)),
  snapshots: (id: number) =>
    unwrap<AccountBalanceSnapshot[]>(api.get(`/api/accounting-closes/${id}/snapshots`)),
  createDraft: (req: AccountingCloseDraftReq) =>
    unwrap<number>(api.post('/api/accounting-closes/draft', req)),
  close: (id: number) =>
    unwrap<AccountingCloseResp>(api.post(`/api/accounting-closes/${id}/close`, {})),
  reopen: (id: number, reopenReason: string) =>
    unwrap<void>(api.post(`/api/accounting-closes/${id}/reopen`, { reopenReason })),
};
