'use server';


import { executeServerAction, type ActionResult } from '@/lib/api/execute-server-action';
import { buildApiUrl } from '@/lib/api/query-params';
import type { PaginatedApiResponse } from '@/lib/api/types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type { Account, AccountCategory, AccountFormData, AccountStatus } from './types';
import { BANK_LABELS } from './types';

// ===== API 응답 타입 =====
interface BankAccountApiData {
  id: number;
  bank_code: string;
  bank_name: string;
  account_number: string;
  account_holder: string;
  account_name: string;
  status: AccountStatus;
  is_primary: boolean;
  assigned_user_id?: number;
  created_at?: string;
  updated_at?: string;
  // 신규 필드
  category?: AccountCategory;
  account_type?: string;
  is_manual?: boolean;
  contract_amount?: number;
  interest_rate?: number;
  start_date?: string;
  maturity_date?: string;
  carryover_balance?: number;
  loan_amount?: number;
  loan_balance?: number;
  interest_payment_cycle?: string;
  repayment_method?: string;
  grace_period?: string;
  monthly_repayment?: number;
  collateral?: string;
  investment_amount?: number;
  return_rate?: number;
  evaluation_amount?: number;
  surrender_value?: number;
  policy_number?: string;
  payment_cycle?: string;
  premium_per_cycle?: number;
  premium_per_person?: number;
  enrolled_count?: number;
  insured_property?: string;
  property_address?: string;
  beneficiary?: string;
  note?: string;
}

type BankAccountPaginatedResponse = PaginatedApiResponse<BankAccountApiData>;

// ===== 데이터 변환 =====
function transformApiToFrontend(apiData: BankAccountApiData): Account {
  return {
    id: apiData.id,
    bankCode: apiData.bank_code,
    bankName: apiData.bank_name || BANK_LABELS[apiData.bank_code] || apiData.bank_code,
    accountNumber: apiData.account_number,
    accountName: apiData.account_name,
    accountHolder: apiData.account_holder,
    status: apiData.status,
    isPrimary: apiData.is_primary,
    assignedUserId: apiData.assigned_user_id,
    createdAt: apiData.created_at || '',
    updatedAt: apiData.updated_at || '',
    category: apiData.category || 'bank_account',
    accountType: apiData.account_type || 'savings',
    isManual: apiData.is_manual ?? true,
    contractAmount: apiData.contract_amount,
    interestRate: apiData.interest_rate,
    startDate: apiData.start_date,
    maturityDate: apiData.maturity_date,
    carryoverBalance: apiData.carryover_balance,
    loanAmount: apiData.loan_amount,
    loanBalance: apiData.loan_balance,
    interestPaymentCycle: apiData.interest_payment_cycle,
    repaymentMethod: apiData.repayment_method,
    gracePeriod: apiData.grace_period,
    monthlyRepayment: apiData.monthly_repayment,
    collateral: apiData.collateral,
    investmentAmount: apiData.investment_amount,
    returnRate: apiData.return_rate,
    evaluationAmount: apiData.evaluation_amount,
    surrenderValue: apiData.surrender_value,
    policyNumber: apiData.policy_number,
    paymentCycle: apiData.payment_cycle,
    premiumPerCycle: apiData.premium_per_cycle,
    premiumPerPerson: apiData.premium_per_person,
    enrolledCount: apiData.enrolled_count,
    insuredProperty: apiData.insured_property,
    propertyAddress: apiData.property_address,
    beneficiary: apiData.beneficiary,
    note: apiData.note,
  };
}

function transformFrontendToApi(data: Partial<AccountFormData>): Record<string, unknown> {
  return {
    // 공통
    category: data.category,
    account_type: data.accountType,
    bank_code: data.bankCode,
    bank_name: data.bankName || BANK_LABELS[data.bankCode || ''] || data.bankCode,
    account_number: data.accountNumber,
    account_holder: data.accountHolder,
    account_name: data.accountName,
    status: data.status,
    // 은행계좌
    contract_amount: data.contractAmount,
    interest_rate: data.interestRate,
    start_date: data.startDate,
    maturity_date: data.maturityDate,
    carryover_balance: data.carryoverBalance,
    // 대출계좌
    loan_amount: data.loanAmount,
    loan_balance: data.loanBalance,
    interest_payment_cycle: data.interestPaymentCycle,
    repayment_method: data.repaymentMethod,
    grace_period: data.gracePeriod,
    monthly_repayment: data.monthlyRepayment,
    collateral: data.collateral,
    // 증권계좌
    investment_amount: data.investmentAmount,
    return_rate: data.returnRate,
    evaluation_amount: data.evaluationAmount,
    // 보험계좌
    surrender_value: data.surrenderValue,
    policy_number: data.policyNumber,
    payment_cycle: data.paymentCycle,
    premium_per_cycle: data.premiumPerCycle,
    premium_per_person: data.premiumPerPerson,
    enrolled_count: data.enrolledCount,
    insured_property: data.insuredProperty,
    property_address: data.propertyAddress,
    beneficiary: data.beneficiary,
    note: data.note,
  };
}

// ===== 계좌 목록 조회 =====
export async function getBankAccounts(params?: {
  page?: number; perPage?: number; search?: string; category?: string;
}): Promise<{
  success: boolean; data?: Account[]; meta?: { currentPage: number; lastPage: number; perPage: number; total: number };
  error?: string; __authError?: boolean;
}> {
  const result = await executeServerAction({
    url: buildApiUrl('/api/v1/bank-accounts', {
      page: params?.page,
      per_page: params?.perPage,
      search: params?.search,
      category: params?.category && params.category !== 'all' ? params.category : undefined,
    }),
    transform: (data: BankAccountPaginatedResponse) => ({
      accounts: (data?.data || []).map(transformApiToFrontend),
      meta: { currentPage: data?.current_page || 1, lastPage: data?.last_page || 1, perPage: data?.per_page || 20, total: data?.total || 0 },
    }),
    errorMessage: '계좌 목록 조회에 실패했습니다.',
  });
  return { success: result.success, data: result.data?.accounts, meta: result.data?.meta, error: result.error, __authError: result.__authError };
}

// ===== 계좌 상세 조회 =====
export async function getBankAccount(id: number): Promise<ActionResult<Account>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-accounts/${id}`),
    transform: (data: BankAccountApiData) => transformApiToFrontend(data),
    errorMessage: '계좌 조회에 실패했습니다.',
  });
}

// ===== 계좌 생성 =====
export async function createBankAccount(data: AccountFormData): Promise<ActionResult<Account>> {
  return executeServerAction({
    url: buildApiUrl('/api/v1/bank-accounts'),
    method: 'POST',
    body: transformFrontendToApi(data),
    transform: (d: BankAccountApiData) => transformApiToFrontend(d),
    errorMessage: '계좌 등록에 실패했습니다.',
  });
}

// ===== 계좌 수정 =====
export async function updateBankAccount(id: number, data: Partial<AccountFormData>): Promise<ActionResult<Account>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-accounts/${id}`),
    method: 'PUT',
    body: transformFrontendToApi(data),
    transform: (d: BankAccountApiData) => transformApiToFrontend(d),
    errorMessage: '계좌 수정에 실패했습니다.',
  });
}

// ===== 계좌 삭제 =====
export async function deleteBankAccount(id: number): Promise<ActionResult> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-accounts/${id}`),
    method: 'DELETE',
    errorMessage: '계좌 삭제에 실패했습니다.',
  });
}

// ===== 계좌 상태 토글 =====
export async function toggleBankAccountStatus(id: number): Promise<ActionResult<Account>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-accounts/${id}/toggle`),
    method: 'PATCH',
    transform: (data: BankAccountApiData) => transformApiToFrontend(data),
    errorMessage: '상태 변경에 실패했습니다.',
  });
}

// ===== 대표 계좌 설정 =====
export async function setPrimaryBankAccount(id: number): Promise<ActionResult<Account>> {
  return executeServerAction({
    url: buildApiUrl(`/api/v1/bank-accounts/${id}/set-primary`),
    method: 'PATCH',
    transform: (data: BankAccountApiData) => transformApiToFrontend(data),
    errorMessage: '대표 계좌 설정에 실패했습니다.',
  });
}

// ===== 다중 삭제 =====
export async function deleteBankAccounts(ids: number[]): Promise<{
  success: boolean; deletedCount?: number; error?: string;
}> {
  try {
    const results = await Promise.all(ids.map(id => deleteBankAccount(id)));
    const successCount = results.filter(r => r.success).length;
    const failedCount = results.filter(r => !r.success).length;

    if (failedCount > 0 && successCount === 0) {
      return { success: false, error: '계좌 삭제에 실패했습니다.' };
    }
    if (failedCount > 0) {
      return { success: true, deletedCount: successCount, error: `${failedCount}개의 계좌 삭제에 실패했습니다.` };
    }
    return { success: true, deletedCount: successCount };
  } catch (error) {
    if (isNextRedirectError(error)) throw error;
    return { success: false, error: '서버 오류가 발생했습니다.' };
  }
}

// ===== 계좌 통계 (클라이언트 사이드 집계) =====
export async function getAccountSummary(): Promise<ActionResult<{
  total: number;
  bankAccount: number;
  loanAccount: number;
  securitiesAccount: number;
  insuranceAccount: number;
}>> {
  const result = await getBankAccounts({ perPage: 9999 });
  if (!result.success || !result.data) {
    return { success: false, error: result.error };
  }
  const accounts = result.data;
  return {
    success: true,
    data: {
      total: accounts.length,
      bankAccount: accounts.filter(a => a.category === 'bank_account').length,
      loanAccount: accounts.filter(a => a.category === 'loan_account').length,
      securitiesAccount: accounts.filter(a => a.category === 'securities_account').length,
      insuranceAccount: accounts.filter(a => a.category === 'insurance_account').length,
    },
  };
}
