/**
 * 세금계산서 관리 - 타입 및 상수 정의
 */

// ===== 탭 구분 =====
export type InvoiceTab = 'sales' | 'purchase';

export const TAB_OPTIONS: { value: InvoiceTab; label: string }[] = [
  { value: 'sales', label: '매출' },
  { value: 'purchase', label: '매입' },
];

// ===== 일자유형 =====
export const DATE_TYPE_OPTIONS = [
  { value: 'write_date', label: '작성일자' },
  { value: 'send_date', label: '전송일자' },
];

// ===== 과세유형 =====
export type TaxType = 'taxable' | 'zero_rate' | 'tax_free';

export const TAX_TYPE_OPTIONS: { value: TaxType; label: string }[] = [
  { value: 'taxable', label: '과세' },
  { value: 'zero_rate', label: '영세' },
  { value: 'tax_free', label: '면세' },
];

export const TAX_TYPE_LABELS: Record<TaxType, string> = {
  taxable: '과세',
  zero_rate: '영세',
  tax_free: '면세',
};

// ===== 영수구분 =====
export type ReceiptType = 'receipt' | 'claim';

export const RECEIPT_TYPE_OPTIONS: { value: ReceiptType; label: string }[] = [
  { value: 'receipt', label: '영수' },
  { value: 'claim', label: '청구' },
];

export const RECEIPT_TYPE_LABELS: Record<ReceiptType, string> = {
  receipt: '영수',
  claim: '청구',
};

// ===== 세금계산서 상태 =====
export type InvoiceStatus = 'pending' | 'journalized' | 'error';

export const INVOICE_STATUS_MAP: Record<InvoiceStatus, { label: string; color: string }> = {
  pending: { label: '미분개', color: 'bg-yellow-100 text-yellow-700' },
  journalized: { label: '분개완료', color: 'bg-green-100 text-green-700' },
  error: { label: '오류', color: 'bg-red-100 text-red-700' },
};

// ===== 소스 구분 (수기/홈택스) =====
export type InvoiceSource = 'manual' | 'hometax';

export const INVOICE_SOURCE_LABELS: Record<InvoiceSource, string> = {
  manual: '수기',
  hometax: '홈택스',
};

// ===== 구분 (매출/매입) =====
export const DIVISION_OPTIONS = [
  { value: 'sales', label: '매출' },
  { value: 'purchase', label: '매입' },
];

// ===== 세금계산서 레코드 (프론트엔드) =====
export interface TaxInvoiceMgmtRecord {
  id: string;
  division: InvoiceTab;
  writeDate: string;
  issueDate: string | null;
  vendorName: string;
  vendorBusinessNumber: string;
  taxType: TaxType;
  itemName: string;
  supplyAmount: number;
  taxAmount: number;
  totalAmount: number;
  receiptType: ReceiptType;
  documentNumber: string;
  status: InvoiceStatus;
  source: InvoiceSource;
  memo: string;
}

// ===== API 응답 타입 (snake_case) =====
export interface TaxInvoiceMgmtApiData {
  id: number;
  division: string;
  write_date: string;
  issue_date: string | null;
  vendor_name: string;
  vendor_business_number: string;
  tax_type: string;
  item_name: string;
  supply_amount: string | number;
  tax_amount: string | number;
  total_amount: string | number;
  receipt_type: string;
  document_number: string;
  status: string;
  source: string;
  memo: string | null;
  created_at: string;
  updated_at: string;
}

// ===== 요약 데이터 =====
export interface TaxInvoiceSummary {
  salesSupplyAmount: number;
  salesTaxAmount: number;
  salesTotalAmount: number;
  salesCount: number;
  purchaseSupplyAmount: number;
  purchaseTaxAmount: number;
  purchaseTotalAmount: number;
  purchaseCount: number;
}

export interface TaxInvoiceSummaryApiData {
  sales_supply_amount: number;
  sales_tax_amount: number;
  sales_total_amount: number;
  sales_count: number;
  purchase_supply_amount: number;
  purchase_tax_amount: number;
  purchase_total_amount: number;
  purchase_count: number;
}

// ===== 분개 항목 =====
export type JournalSide = 'debit' | 'credit';

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

export interface JournalEntryRow {
  id: string;
  side: JournalSide;
  accountSubject: string;
  debitAmount: number;
  creditAmount: number;
}

export interface JournalEntryData {
  invoiceId: string;
  rows: JournalEntryRow[];
}

// ===== 카드 내역 레코드 =====
export interface CardHistoryRecord {
  id: string;
  transactionDate: string;
  merchantName: string;
  amount: number;
  approvalNumber: string;
  businessNumber: string;
}

export interface CardHistoryApiData {
  id: number;
  transaction_date: string;
  merchant_name: string;
  amount: string | number;
  approval_number: string;
  business_number: string;
}

// ===== 수기 입력 폼 데이터 =====
export interface ManualEntryFormData {
  division: InvoiceTab;
  writeDate: string;
  vendorName: string;
  vendorBusinessNumber: string;
  supplyAmount: number;
  taxAmount: number;
  totalAmount: number;
  itemName: string;
  taxType: TaxType;
  memo: string;
}

// ===== 계정과목 옵션 =====
export const ACCOUNT_SUBJECT_OPTIONS = [
  { value: '', label: '선택' },
  { value: 'sales', label: '매출' },
  { value: 'purchasePayment', label: '매입대금' },
  { value: 'salesVat', label: '부가세예수금' },
  { value: 'purchaseVat', label: '부가세대급금' },
  { value: 'accountsReceivable', label: '외상매출금' },
  { value: 'accountsPayable', label: '외상매입금' },
  { value: 'cashAndDeposits', label: '현금및예금' },
  { value: 'advance', label: '선급금' },
  { value: 'advanceReceived', label: '선수금' },
  { value: 'other', label: '기타' },
];

// ===== API → Frontend 변환 =====
export function transformApiToFrontend(apiData: TaxInvoiceMgmtApiData): TaxInvoiceMgmtRecord {
  return {
    id: String(apiData.id),
    division: apiData.division as InvoiceTab,
    writeDate: apiData.write_date,
    issueDate: apiData.issue_date,
    vendorName: apiData.vendor_name,
    vendorBusinessNumber: apiData.vendor_business_number,
    taxType: apiData.tax_type as TaxType,
    itemName: apiData.item_name,
    supplyAmount: Number(apiData.supply_amount),
    taxAmount: Number(apiData.tax_amount),
    totalAmount: Number(apiData.total_amount),
    receiptType: apiData.receipt_type as ReceiptType,
    documentNumber: apiData.document_number,
    status: apiData.status as InvoiceStatus,
    source: apiData.source as InvoiceSource,
    memo: apiData.memo || '',
  };
}

// ===== Frontend → API 변환 =====
export function transformFrontendToApi(data: ManualEntryFormData): Record<string, unknown> {
  return {
    division: data.division,
    write_date: data.writeDate,
    vendor_name: data.vendorName,
    vendor_business_number: data.vendorBusinessNumber,
    supply_amount: data.supplyAmount,
    tax_amount: data.taxAmount,
    total_amount: data.totalAmount,
    item_name: data.itemName,
    tax_type: data.taxType,
    memo: data.memo || null,
  };
}

// ===== 카드 내역 API → Frontend 변환 =====
export function transformCardHistoryApi(apiData: CardHistoryApiData): CardHistoryRecord {
  return {
    id: String(apiData.id),
    transactionDate: apiData.transaction_date,
    merchantName: apiData.merchant_name,
    amount: Number(apiData.amount),
    approvalNumber: apiData.approval_number,
    businessNumber: apiData.business_number,
  };
}

// ===== 요약 API → Frontend 변환 =====
export function transformSummaryApi(apiData: TaxInvoiceSummaryApiData): TaxInvoiceSummary {
  return {
    salesSupplyAmount: apiData.sales_supply_amount,
    salesTaxAmount: apiData.sales_tax_amount,
    salesTotalAmount: apiData.sales_total_amount,
    salesCount: apiData.sales_count,
    purchaseSupplyAmount: apiData.purchase_supply_amount,
    purchaseTaxAmount: apiData.purchase_tax_amount,
    purchaseTotalAmount: apiData.purchase_total_amount,
    purchaseCount: apiData.purchase_count,
  };
}
