'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 { BankTransaction, TransactionKind, TransactionFormData, AccountCategoryFilter } from './types';

// ===== API 응답 타입 =====
interface BankTransactionApiItem {
  id: number;
  type: 'deposit' | 'withdrawal';
  transaction_date: string;
  transaction_time?: string | null;
  bank_account_id: number;
  bank_name: string;
  account_name: string;
  account_number?: string | null;
  note: string | null;
  vendor_id: number | null;
  vendor_name: string | null;
  depositor_name: string | null;
  deposit_amount: number | string;
  withdrawal_amount: number | string;
  balance: number | string;
  transaction_type: string | null;
  source_id: string;
  memo?: string | null;
  branch?: string | null;
  is_manual?: boolean;
  modified_fields?: string[] | null;
  created_at: string;
  updated_at: string;
}

interface BankTransactionApiSummary {
  total_deposit: number;
  total_withdrawal: number;
  total_balance: number;
  account_count: number;
  unset_count: number;
  deposit_unset_count: number;
  withdrawal_unset_count: number;
}

// ===== API → Frontend 변환 =====
function transformItem(item: BankTransactionApiItem): BankTransaction {
  return {
    id: `${item.type}-${item.id}`,
    bankName: item.bank_name,
    accountName: item.account_name,
    accountNumber: item.account_number || undefined,
    transactionDate: item.transaction_date,
    transactionTime: item.transaction_time || undefined,
    type: item.type as TransactionKind,
    note: item.note || undefined,
    vendorId: item.vendor_id ? String(item.vendor_id) : undefined,
    vendorName: item.vendor_name || undefined,
    depositorName: item.depositor_name || undefined,
    depositAmount: typeof item.deposit_amount === 'string' ? parseFloat(item.deposit_amount) : item.deposit_amount,
    withdrawalAmount: typeof item.withdrawal_amount === 'string' ? parseFloat(item.withdrawal_amount) : item.withdrawal_amount,
    balance: typeof item.balance === 'string' ? parseFloat(item.balance) : item.balance,
    transactionType: item.transaction_type || undefined,
    sourceId: item.source_id,
    bankAccountId: item.bank_account_id,
    memo: item.memo || undefined,
    branch: item.branch || undefined,
    isManual: !!item.is_manual,
    modifiedFields: item.modified_fields || undefined,
    createdAt: item.created_at,
    updatedAt: item.updated_at,
  };
}

// ===== 입출금 통합 목록 조회 =====
export async function getBankTransactionList(params?: {
  page?: number; perPage?: number; startDate?: string; endDate?: string;
  bankAccountId?: number; transactionType?: string; search?: string;
  sortBy?: string; sortDir?: 'asc' | 'desc';
  accountCategory?: AccountCategoryFilter; financialInstitution?: string;
}) {
  return executePaginatedAction<BankTransactionApiItem, BankTransaction>({
    url: buildApiUrl('/api/v1/bank-transactions', {
      page: params?.page,
      per_page: params?.perPage,
      start_date: params?.startDate,
      end_date: params?.endDate,
      bank_account_id: params?.bankAccountId,
      transaction_type: params?.transactionType,
      search: params?.search,
      sort_by: params?.sortBy,
      sort_dir: params?.sortDir,
      account_category: params?.accountCategory !== 'all' ? params?.accountCategory : undefined,
      financial_institution: params?.financialInstitution !== 'all' ? params?.financialInstitution : undefined,
    }),
    transform: transformItem,
    errorMessage: '은행 거래 조회에 실패했습니다.',
  });
}

// ===== 입출금 요약 통계 =====
export interface BankTransactionSummaryData {
  totalDeposit: number;
  totalWithdrawal: number;
  totalBalance: number;
  accountCount: number;
  unsetCount: number;
}

export async function getBankTransactionSummary(params?: {
  startDate?: string; endDate?: string;
}): Promise<ActionResult<BankTransactionSummaryData>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bank-transactions/summary', {
      start_date: params?.startDate,
      end_date: params?.endDate,
    }),
    transform: (data: BankTransactionApiSummary) => ({
      totalDeposit: data.total_deposit,
      totalWithdrawal: data.total_withdrawal,
      totalBalance: data.total_balance ?? 0,
      accountCount: data.account_count ?? 0,
      unsetCount: data.unset_count ?? (data.deposit_unset_count + data.withdrawal_unset_count),
    }),
    errorMessage: '요약 조회에 실패했습니다.',
  });
}

// ===== 계좌 목록 조회 (필터 + 모달 Select용) =====
export async function getBankAccountOptions(): Promise<{
  success: boolean; data: { id: number; label: string }[]; error?: string;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/bank-transactions/accounts'),
    transform: (data: { id: number; label: string }[]) => data,
    errorMessage: '계좌 목록 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data || [], error: result.error };
}

// ===== 금융기관 목록 조회 (⑤ 필터용) =====
export async function getFinancialInstitutions(): Promise<{
  success: boolean; data: { value: string; label: string }[]; error?: string;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/bank-transactions/financial-institutions'),
    transform: (data: { code: string; name: string }[]) =>
      data.map((item) => ({ value: item.code, label: item.name })),
    errorMessage: '금융기관 목록 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data || [], error: result.error };
}

// ===== 수기 입력 (신규 생성) =====
export async function createManualTransaction(
  formData: TransactionFormData
): Promise<ActionResult<BankTransaction>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bank-transactions/manual'),
    method: 'POST',
    body: {
      bank_account_id: formData.bankAccountId,
      transaction_date: formData.transactionDate,
      transaction_time: formData.transactionTime || undefined,
      type: formData.type,
      amount: formData.amount,
      note: formData.note || undefined,
      depositor_name: formData.depositorName || undefined,
      memo: formData.memo || undefined,
      branch: formData.branch || undefined,
    },
    transform: transformItem,
    errorMessage: '수기 입력에 실패했습니다.',
  });
}

// ===== 거래 수정 =====
export async function updateTransaction(
  id: string,
  formData: Partial<TransactionFormData>
): Promise<ActionResult<BankTransaction>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-transactions/${id}`),
    method: 'PUT',
    body: {
      bank_account_id: formData.bankAccountId,
      transaction_date: formData.transactionDate,
      transaction_time: formData.transactionTime || undefined,
      type: formData.type,
      amount: formData.amount,
      note: formData.note ?? undefined,
      depositor_name: formData.depositorName ?? undefined,
      memo: formData.memo ?? undefined,
      branch: formData.branch ?? undefined,
    },
    transform: transformItem,
    errorMessage: '거래 수정에 실패했습니다.',
  });
}

// ===== 거래 삭제 =====
export async function deleteTransaction(id: string): Promise<ActionResult<null>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-transactions/${id}`),
    method: 'DELETE',
    errorMessage: '거래 삭제에 실패했습니다.',
  });
}

// ===== 원본으로 복원 =====
export async function restoreTransaction(id: string): Promise<ActionResult<BankTransaction>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-transactions/${id}/restore`),
    method: 'POST',
    transform: transformItem,
    errorMessage: '원본 복원에 실패했습니다.',
  });
}

// ===== 변경사항 일괄 저장 =====
export async function batchSaveTransactions(
  changes: { id: string; data: Partial<TransactionFormData> }[]
): Promise<ActionResult<null>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bank-transactions/batch-save'),
    method: 'POST',
    body: {
      transactions: changes.map((c) => ({
        id: c.id,
        ...c.data,
      })),
    },
    errorMessage: '일괄 저장에 실패했습니다.',
  });
}

// ===== 엑셀 다운로드 =====
export async function exportBankTransactionsExcel(params?: {
  startDate?: string; endDate?: string;
  accountCategory?: string; financialInstitution?: string;
}): Promise<ActionResult<{ downloadUrl: string }>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bank-transactions/export', {
      start_date: params?.startDate,
      end_date: params?.endDate,
      account_category: params?.accountCategory,
      financial_institution: params?.financialInstitution,
    }),
    transform: (data: { download_url: string }) => ({
      downloadUrl: data.download_url,
    }),
    errorMessage: '엑셀 다운로드에 실패했습니다.',
  });
}
