'use server';

import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { executePaginatedAction } from '@/lib/api/execute-paginated-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type {
  TaxInvoiceMgmtRecord,
  TaxInvoiceMgmtApiData,
  TaxInvoiceSummary,
  TaxInvoiceSummaryApiData,
  CardHistoryRecord,
  CardHistoryApiData,
  ManualEntryFormData,
  JournalEntryRow,
} from './types';
import {
  transformApiToFrontend,
  transformFrontendToApi,
  transformCardHistoryApi,
  transformSummaryApi,
} from './types';

// ===== 세금계산서 목록 Mock =====
// TODO: 실제 API 연동 시 Mock 제거
const MOCK_INVOICES: TaxInvoiceMgmtRecord[] = [
  { id: '1', division: 'sales', writeDate: '2026-01-15', issueDate: '2026-01-16', vendorName: '(주)삼성전자', vendorBusinessNumber: '124-81-00998', taxType: 'taxable', itemName: '전자부품', supplyAmount: 500000, taxAmount: 50000, totalAmount: 550000, receiptType: 'receipt', documentNumber: 'TI-001', status: 'journalized', source: 'hometax', memo: '' },
  { id: '2', division: 'sales', writeDate: '2026-01-20', issueDate: '2026-01-20', vendorName: '현대건설(주)', vendorBusinessNumber: '211-85-12345', taxType: 'taxable', itemName: '건축자재', supplyAmount: 1200000, taxAmount: 120000, totalAmount: 1320000, receiptType: 'claim', documentNumber: 'TI-002', status: 'pending', source: 'hometax', memo: '' },
  { id: '3', division: 'sales', writeDate: '2026-02-03', issueDate: null, vendorName: '(주)한국사무용품', vendorBusinessNumber: '107-86-55432', taxType: 'taxable', itemName: '사무용품', supplyAmount: 300000, taxAmount: 30000, totalAmount: 330000, receiptType: 'receipt', documentNumber: '', status: 'pending', source: 'manual', memo: '수기 입력' },
  { id: '4', division: 'purchase', writeDate: '2026-01-10', issueDate: '2026-01-11', vendorName: 'CJ대한통운', vendorBusinessNumber: '110-81-28388', taxType: 'taxable', itemName: '운송비', supplyAmount: 40000, taxAmount: 4000, totalAmount: 44000, receiptType: 'receipt', documentNumber: 'TI-003', status: 'journalized', source: 'hometax', memo: '' },
  { id: '5', division: 'purchase', writeDate: '2026-02-01', issueDate: '2026-02-01', vendorName: '스타벅스 역삼역점', vendorBusinessNumber: '201-86-99012', taxType: 'tax_free', itemName: '복리후생', supplyAmount: 14000, taxAmount: 1400, totalAmount: 15400, receiptType: 'receipt', documentNumber: 'TI-004', status: 'pending', source: 'hometax', memo: '' },
  { id: '6', division: 'purchase', writeDate: '2026-02-10', issueDate: null, vendorName: '(주)코스트코코리아', vendorBusinessNumber: '301-81-67890', taxType: 'taxable', itemName: '비품', supplyAmount: 200000, taxAmount: 20000, totalAmount: 220000, receiptType: 'claim', documentNumber: '', status: 'error', source: 'manual', memo: '수기 입력' },
];

// ===== 세금계산서 목록 조회 =====
export async function getTaxInvoices(params: {
  division?: string;
  dateType?: string;
  startDate?: string;
  endDate?: string;
  vendorSearch?: string;
  page?: number;
  perPage?: number;
}) {
  // TODO: 실제 API 연동 시 아래 코드로 교체
  // return executePaginatedAction<TaxInvoiceMgmtApiData, TaxInvoiceMgmtRecord>({
  //   url: buildApiUrl('/api/v1/tax-invoices', { ... }),
  //   transform: transformApiToFrontend,
  //   errorMessage: '세금계산서 목록 조회에 실패했습니다.',
  // });
  const filtered = MOCK_INVOICES.filter((inv) => inv.division === (params.division || 'sales'));
  return {
    success: true as const,
    data: filtered,
    error: undefined as string | undefined,
    pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: filtered.length },
  };
}

// ===== 세금계산서 요약 조회 =====
export async function getTaxInvoiceSummary(_params: {
  dateType?: string;
  startDate?: string;
  endDate?: string;
  vendorSearch?: string;
}): Promise<ActionResult<TaxInvoiceSummary>> {
  // TODO: 실제 API 연동 시 아래 코드로 교체
  // return executeServerAction({ ... });
  const sales = MOCK_INVOICES.filter((inv) => inv.division === 'sales');
  const purchase = MOCK_INVOICES.filter((inv) => inv.division === 'purchase');
  return {
    success: true,
    data: {
      salesSupplyAmount: sales.reduce((s, i) => s + i.supplyAmount, 0),
      salesTaxAmount: sales.reduce((s, i) => s + i.taxAmount, 0),
      salesTotalAmount: sales.reduce((s, i) => s + i.totalAmount, 0),
      salesCount: sales.length,
      purchaseSupplyAmount: purchase.reduce((s, i) => s + i.supplyAmount, 0),
      purchaseTaxAmount: purchase.reduce((s, i) => s + i.taxAmount, 0),
      purchaseTotalAmount: purchase.reduce((s, i) => s + i.totalAmount, 0),
      purchaseCount: purchase.length,
    },
  };
}

// ===== 세금계산서 수기 등록 =====
export async function createTaxInvoice(
  data: ManualEntryFormData
): Promise<ActionResult<TaxInvoiceMgmtRecord>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/tax-invoices'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (d: TaxInvoiceMgmtApiData) => transformApiToFrontend(d),
    errorMessage: '세금계산서 등록에 실패했습니다.',
  });
}

// ===== 카드 내역 조회 =====
// TODO: 실제 API 연동 시 Mock 제거
const MOCK_CARD_HISTORY: CardHistoryRecord[] = [
  { id: '1', transactionDate: '2026-01-20', merchantName: '(주)삼성전자', amount: 550000, approvalNumber: 'AP-20260120-001', businessNumber: '124-81-00998' },
  { id: '2', transactionDate: '2026-01-25', merchantName: '현대오일뱅크 강남점', amount: 82500, approvalNumber: 'AP-20260125-003', businessNumber: '211-85-12345' },
  { id: '3', transactionDate: '2026-02-03', merchantName: '(주)한국사무용품', amount: 330000, approvalNumber: 'AP-20260203-007', businessNumber: '107-86-55432' },
  { id: '4', transactionDate: '2026-02-10', merchantName: 'CJ대한통운', amount: 44000, approvalNumber: 'AP-20260210-012', businessNumber: '110-81-28388' },
  { id: '5', transactionDate: '2026-02-14', merchantName: '스타벅스 역삼역점', amount: 15400, approvalNumber: 'AP-20260214-019', businessNumber: '201-86-99012' },
];

export async function getCardHistory(_params: {
  startDate?: string;
  endDate?: string;
  search?: string;
  page?: number;
  perPage?: number;
}): Promise<ActionResult<CardHistoryRecord[]>> {
  // TODO: 실제 API 연동 시 아래 코드로 교체
  // return executePaginatedAction<CardHistoryApiData, CardHistoryRecord>({
  //   url: buildApiUrl('/api/v1/card-transactions/history', {
  //     start_date: _params.startDate,
  //     end_date: _params.endDate,
  //     search: _params.search || undefined,
  //     page: _params.page,
  //     per_page: _params.perPage,
  //   }),
  //   transform: transformCardHistoryApi,
  //   errorMessage: '카드 내역 조회에 실패했습니다.',
  // });
  return { success: true, data: MOCK_CARD_HISTORY };
}

// ===== 분개 내역 조회 =====
export async function getJournalEntries(invoiceId: string): Promise<ActionResult<{
  rows: { id: string; side: string; account_subject: string; debit_amount: number; credit_amount: number }[];
}>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/tax-invoices/${invoiceId}/journal-entries`),
    errorMessage: '분개 내역 조회에 실패했습니다.',
  });
}

// ===== 분개 수정 =====
export async function updateJournalEntry(
  invoiceId: string,
  rows: JournalEntryRow[]
): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/tax-invoices/${invoiceId}/journal-entries`),
    method: 'PUT',
    body: {
      rows: rows.map((r) => ({
        side: r.side,
        account_subject: r.accountSubject,
        debit_amount: r.debitAmount,
        credit_amount: r.creditAmount,
      })),
    },
    errorMessage: '분개 수정에 실패했습니다.',
  });
}

// ===== 분개 삭제 =====
export async function deleteJournalEntry(invoiceId: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/tax-invoices/${invoiceId}/journal-entries`),
    method: 'DELETE',
    errorMessage: '분개 삭제에 실패했습니다.',
  });
}

// ===== 엑셀 다운로드 =====
export async function downloadTaxInvoiceExcel(params: {
  division?: string;
  dateType?: string;
  startDate?: string;
  endDate?: string;
  vendorSearch?: string;
}): Promise<ActionResult<{ url: string }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/tax-invoices/export', {
      division: params.division,
      date_type: params.dateType,
      start_date: params.startDate,
      end_date: params.endDate,
      vendor_search: params.vendorSearch || undefined,
    }),
    errorMessage: '엑셀 다운로드에 실패했습니다.',
  });
}
