'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 { DepositRecord, DepositType, DepositStatus } from './types';

// ===== API 응답 타입 =====
interface DepositApiData {
  id: number;
  tenant_id: number;
  deposit_date: string;
  amount: number | string;
  client_id: number | null;
  client_name: string | null;
  bank_account_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;
}

// ===== API → Frontend 변환 =====
function transformApiToFrontend(apiData: DepositApiData): DepositRecord {
  return {
    id: String(apiData.id),
    depositDate: apiData.deposit_date,
    depositAmount: 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}` : '',
    depositorName: apiData.client_name || apiData.client?.name || '',
    note: apiData.description || '',
    depositType: (apiData.account_code || 'unset') as DepositType,
    vendorId: apiData.client_id ? String(apiData.client_id) : '',
    vendorName: apiData.client?.name || apiData.client_name || '',
    status: 'inputWaiting' as DepositStatus,
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

// ===== Frontend → API 변환 =====
function transformFrontendToApi(data: Partial<DepositRecord>): Record<string, unknown> {
  const result: Record<string, unknown> = {};
  if (data.depositDate !== undefined) result.deposit_date = data.depositDate;
  if (data.depositAmount !== undefined) result.amount = data.depositAmount;
  if (data.depositorName !== undefined) result.client_name = data.depositorName;
  if (data.note !== undefined) result.description = data.note || null;
  if (data.depositType !== undefined) {
    result.account_code = data.depositType === 'unset' ? null : data.depositType;
  }
  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 getDeposits(params?: {
  page?: number; perPage?: number; startDate?: string; endDate?: string;
  depositType?: string; vendor?: string; search?: string;
}) {
  return executePaginatedAction<DepositApiData, DepositRecord>({
    url: buildApiUrl('/api/v1/deposits', {
      page: params?.page,
      per_page: params?.perPage,
      start_date: params?.startDate,
      end_date: params?.endDate,
      deposit_type: params?.depositType !== 'all' ? params?.depositType : undefined,
      vendor: params?.vendor !== 'all' ? params?.vendor : undefined,
      search: params?.search,
    }),
    transform: transformApiToFrontend,
    errorMessage: '입금 내역 조회에 실패했습니다.',
  });
}

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

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

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

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

// ===== 입금 수정 =====
export async function updateDeposit(id: string, data: Partial<DepositRecord>): Promise<ActionResult<DepositRecord>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/deposits/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: (data: DepositApiData) => 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 };
}
