/**
 * 일반전표입력 - 타입 및 상수 정의
 */

import { getLocalDateString } from '@/lib/utils/date';

// ===== 전표 구분 =====
export type JournalDivision = 'deposit' | 'withdrawal' | 'transfer' | 'manual';

export const JOURNAL_DIVISION_LABELS: Record<JournalDivision, string> = {
  deposit: '입금',
  withdrawal: '출금',
  transfer: '대체',
  manual: '수기',
};

// ===== 전표 소스 (수기/연동) =====
export type JournalSource = 'manual' | 'linked';

export const JOURNAL_SOURCE_MAP: Record<JournalSource, { label: string; color: string }> = {
  manual: { label: '수기 전표', color: 'bg-orange-400' },
  linked: { label: '연동 전표', color: 'bg-blue-400' },
};

// ===== 기간 버튼 =====
export const PERIOD_BUTTONS = [
  { value: 'this_month', label: '이번달' },
  { value: 'last_month', label: '지난달' },
  { value: 'd2', label: 'D-2일' },
  { value: 'd3', label: 'D-3일' },
  { value: 'd4', label: 'D-4일' },
  { value: 'd5', label: 'D-5일' },
] as const;

export type PeriodButtonValue = (typeof PERIOD_BUTTONS)[number]['value'];

// ===== 분개 구분 (차변/대변) =====
export type JournalSide = 'debit' | 'credit';

export const JOURNAL_SIDE_OPTIONS: { value: JournalSide; label: string }[] = [
  { value: 'debit', label: '차변' },
  { value: 'credit', label: '대변' },
];

// ===== 메인 리스트 레코드 (프론트엔드 camelCase) =====
export interface GeneralJournalRecord {
  id: string;
  date: string;
  division: JournalDivision;
  amount: number;
  description: string;
  journalDescription: string;
  depositAmount: number;
  withdrawalAmount: number;
  balance: number;
  debitAmount: number;
  creditAmount: number;
  source: JournalSource;
}

// ===== API 응답 (snake_case) =====
export interface GeneralJournalApiData {
  id: number;
  date: string;
  division: string;
  amount: string | number;
  description: string;
  journal_description: string;
  deposit_amount?: string | number;
  withdrawal_amount?: string | number;
  balance?: string | number;
  debit_amount: string | number;
  credit_amount: string | number;
  source: string;
  created_at: string;
  updated_at: string;
}

// ===== 요약 통계 =====
export interface GeneralJournalSummary {
  totalCount: number;
  depositCount: number;
  depositAmount: number;
  withdrawalCount: number;
  withdrawalAmount: number;
  journalCompleteCount: number;
  journalIncompleteCount: number;
}

export interface GeneralJournalSummaryApiData {
  total_count?: number;
  deposit_count: number;
  deposit_amount: number;
  withdrawal_count: number;
  withdrawal_amount: number;
  journal_complete_count?: number;
  journal_incomplete_count?: number;
}

// ===== 분개 행 =====
export interface JournalEntryRow {
  id: string;
  side: JournalSide;
  accountSubjectId: string;
  accountSubjectName: string;
  vendorId: string;
  vendorName: string;
  debitAmount: number;
  creditAmount: number;
  memo: string;
}

// ===== 수기 전표 입력 폼 =====
export interface ManualJournalFormData {
  journalDate: string;
  journalNumber: string;
  description: string;
  rows: JournalEntryRow[];
}

// ===== 분개 수정용 거래 정보 (읽기전용) =====
export interface JournalEditData {
  id: string;
  date: string;
  division: JournalDivision;
  amount: number;
  description: string;
  bankName: string;
  accountNumber: string;
}

// ===== 거래처 옵션 =====
export interface VendorOption {
  id: string;
  name: string;
}

// ===== API → Frontend 변환 =====
export function transformApiToFrontend(apiData: GeneralJournalApiData): GeneralJournalRecord {
  const amount = Number(apiData.amount);
  const division = apiData.division as JournalDivision;
  return {
    id: String(apiData.id),
    date: apiData.date,
    division,
    amount,
    description: apiData.description || '',
    journalDescription: apiData.journal_description || '',
    depositAmount: apiData.deposit_amount != null ? Number(apiData.deposit_amount) : (division === 'deposit' ? amount : 0),
    withdrawalAmount: apiData.withdrawal_amount != null ? Number(apiData.withdrawal_amount) : (division === 'withdrawal' ? amount : 0),
    balance: apiData.balance != null ? Number(apiData.balance) : 0,
    debitAmount: Number(apiData.debit_amount),
    creditAmount: Number(apiData.credit_amount),
    source: apiData.source as JournalSource,
  };
}

// ===== 요약 API → Frontend 변환 =====
export function transformSummaryApi(apiData: GeneralJournalSummaryApiData): GeneralJournalSummary {
  const depositCount = apiData.deposit_count;
  const withdrawalCount = apiData.withdrawal_count;
  const totalCount = apiData.total_count ?? (depositCount + withdrawalCount);
  const journalCompleteCount = apiData.journal_complete_count ?? 0;
  const journalIncompleteCount = apiData.journal_incomplete_count ?? (totalCount - journalCompleteCount);
  return {
    totalCount,
    depositCount,
    depositAmount: apiData.deposit_amount,
    withdrawalCount,
    withdrawalAmount: apiData.withdrawal_amount,
    journalCompleteCount,
    journalIncompleteCount,
  };
}

// ===== 기간 버튼 → 날짜 변환 =====
export function getPeriodDates(period: PeriodButtonValue): { start: string; end: string } {
  const today = new Date();
  const formatDate = (d: Date) => getLocalDateString(d);

  switch (period) {
    case 'this_month': {
      const start = new Date(today.getFullYear(), today.getMonth(), 1);
      return { start: formatDate(start), end: formatDate(today) };
    }
    case 'last_month': {
      const start = new Date(today.getFullYear(), today.getMonth() - 1, 1);
      const end = new Date(today.getFullYear(), today.getMonth(), 0);
      return { start: formatDate(start), end: formatDate(end) };
    }
    case 'd2': {
      const d = new Date(today);
      d.setDate(d.getDate() - 2);
      return { start: formatDate(d), end: formatDate(today) };
    }
    case 'd3': {
      const d = new Date(today);
      d.setDate(d.getDate() - 3);
      return { start: formatDate(d), end: formatDate(today) };
    }
    case 'd4': {
      const d = new Date(today);
      d.setDate(d.getDate() - 4);
      return { start: formatDate(d), end: formatDate(today) };
    }
    case 'd5': {
      const d = new Date(today);
      d.setDate(d.getDate() - 5);
      return { start: formatDate(d), end: formatDate(today) };
    }
    default:
      return { start: formatDate(today), end: formatDate(today) };
  }
}
