'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 { fetchVendorOptions, fetchBankAccountOptions } from '@/lib/api/shared-lookups';
import type { WithdrawalRecord, WithdrawalType } from './types';

// ===== API 응답 타입 =====
interface WithdrawalApiData {
  id: number;
  tenant_id: number;
  withdrawal_date: string;
  used_at: string | null;
  amount: number | string;
  client_id: number | null;
  client_name: string | null;
  merchant_name: string | null;
  bank_account_id: number | null;
  card_id: number | null;
  payment_method: string | null;
  account_code: string | null;
  description: string | null;
  reference_type: string | null;
  reference_id: number | null;
  created_at: string;
  updated_at: string;
  client?: { id: number; name: string } | null;
  bank_account?: { id: number; bank_name: string; account_name: string } | null;
  card?: { id: number; card_name: string } | null;
}

// ===== API → Frontend 변환 =====
function transformApiToFrontend(apiData: WithdrawalApiData): WithdrawalRecord {
  return {
    id: String(apiData.id),
    withdrawalDate: apiData.withdrawal_date,
    withdrawalAmount: typeof apiData.amount === 'string' ? parseFloat(apiData.amount) : (apiData.amount ?? 0),
    bankAccountId: apiData.bank_account_id ? String(apiData.bank_account_id) : '',
    accountName: apiData.bank_account ? `${apiData.bank_account.bank_name} ${apiData.bank_account.account_name}` : '',
    recipientName: apiData.merchant_name || apiData.client_name || apiData.client?.name || '',
    note: apiData.description || '',
    withdrawalType: (apiData.account_code || 'unset') as WithdrawalType,
    vendorId: apiData.client_id ? String(apiData.client_id) : '',
    vendorName: apiData.client?.name || apiData.client_name || '',
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

// ===== Frontend → API 변환 =====
function transformFrontendToApi(data: Partial<WithdrawalRecord>): Record<string, unknown> {
  const result: Record<string, unknown> = {};
  if (data.withdrawalDate !== undefined) result.withdrawal_date = data.withdrawalDate;
  if (data.withdrawalAmount !== undefined) result.amount = data.withdrawalAmount;
  if (data.recipientName !== undefined) result.client_name = data.recipientName;
  if (data.note !== undefined) result.description = data.note || null;
  if (data.withdrawalType !== undefined) {
    result.account_code = data.withdrawalType === 'unset' ? null : data.withdrawalType;
  }
  if (data.vendorId !== undefined) result.client_id = data.vendorId ? parseInt(data.vendorId, 10) : null;
  if (data.bankAccountId !== undefined) {
    result.bank_account_id = data.bankAccountId ? parseInt(data.bankAccountId, 10) : null;
  }
  result.payment_method = 'transfer';
  return result;
}

// ===== 출금 내역 조회 =====
export async function getWithdrawals(params?: {
  page?: number; perPage?: number; startDate?: string; endDate?: string;
  withdrawalType?: string; vendor?: string; search?: string;
}) {
  return executePaginatedAction<WithdrawalApiData, WithdrawalRecord>({
    url: buildApiUrl('/api/v1/withdrawals', {
      page: params?.page,
      per_page: params?.perPage,
      start_date: params?.startDate,
      end_date: params?.endDate,
      withdrawal_type: params?.withdrawalType !== 'all' ? params?.withdrawalType : undefined,
      vendor: params?.vendor !== 'all' ? params?.vendor : undefined,
      search: params?.search,
    }),
    transform: transformApiToFrontend,
    errorMessage: '출금 내역 조회에 실패했습니다.',
  });
}

// ===== 출금 내역 삭제 =====
export async function deleteWithdrawal(id: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/withdrawals/${id}`),
    method: 'DELETE',
    errorMessage: '출금 내역 삭제에 실패했습니다.',
  });
}

// ===== 계정과목명 일괄 저장 =====
export async function updateWithdrawalTypes(ids: string[], withdrawalType: string): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/withdrawals/bulk-update-type'),
    method: 'PUT',
    body: { ids: ids.map(id => parseInt(id, 10)), withdrawal_type: withdrawalType },
    errorMessage: '계정과목명 저장에 실패했습니다.',
  });
}

// ===== 출금 상세 조회 =====
export async function getWithdrawalById(id: string): Promise<ActionResult<WithdrawalRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/withdrawals/${id}`),
    transform: (data: WithdrawalApiData) => transformApiToFrontend(data),
    errorMessage: '출금 내역 조회에 실패했습니다.',
  });
}

// ===== 출금 등록 =====
export async function createWithdrawal(data: Partial<WithdrawalRecord>): Promise<ActionResult<WithdrawalRecord>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/withdrawals'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (data: WithdrawalApiData) => transformApiToFrontend(data),
    errorMessage: '출금 등록에 실패했습니다.',
  });
}

// ===== 출금 수정 =====
export async function updateWithdrawal(id: string, data: Partial<WithdrawalRecord>): Promise<ActionResult<WithdrawalRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/withdrawals/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: (data: WithdrawalApiData) => transformApiToFrontend(data),
    errorMessage: '출금 수정에 실패했습니다.',
  });
}

// ===== 거래처 목록 조회 =====
export async function getVendors(): Promise<{
  success: boolean; data: { id: string; name: string }[]; error?: string;
}> {
  const result = await fetchVendorOptions();
  return { success: result.success, data: result.data || [], error: result.error };
}

// ===== 계좌 목록 조회 =====
export async function getBankAccounts(): Promise<{
  success: boolean; data: { id: string; name: string }[]; error?: string;
}> {
  const result = await fetchBankAccountOptions();
  return { success: result.success, data: result.data || [], error: result.error };
}
