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

// ===== 탭 구분 =====
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 = 'draft' | 'issued' | 'sent' | 'cancelled' | 'failed';

export const INVOICE_STATUS_MAP: Record<InvoiceStatus, { label: string; color: string }> = {
  draft: { label: '임시저장', color: 'bg-gray-100 text-gray-700' },
  issued: { label: '발급완료', color: 'bg-blue-100 text-blue-700' },
  sent: { label: '전송완료', color: 'bg-green-100 text-green-700' },
  cancelled: { label: '취소', color: 'bg-red-100 text-red-700' },
  failed: { label: '실패', color: 'bg-orange-100 text-orange-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 응답 타입 (백엔드 TaxInvoice 모델 기준) =====
export interface TaxInvoiceMgmtApiData {
  id: number;
  direction: string;
  supplier_corp_num: string | null;
  supplier_corp_name: string | null;
  buyer_corp_num: string | null;
  buyer_corp_name: string | null;
  issue_date: string | null;
  supply_amount: string | number;
  tax_amount: string | number;
  total_amount: string | number;
  status: string;
  invoice_type: string | null;
  issue_type: string | null;
  nts_confirm_num: string | null;
  description: string | null;
  barobill_invoice_id: string | null;
  items: Array<{ name?: string; [key: string]: unknown }> | 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;
}

// 백엔드 summary API는 by_direction 중첩 구조로 응답
interface DirectionSummary {
  count: number;
  supply_amount: number;
  tax_amount: number;
  total_amount: number;
}

export interface TaxInvoiceSummaryApiData {
  by_direction: {
    sales: DirectionSummary;
    purchases: DirectionSummary;
  };
  by_status: Record<string, 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;
  used_at: string;
  merchant_name: string;
  amount: string | number;
  approval_number?: string;
  business_number?: string;
  description?: string | null;
}

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

// ===== API → Frontend 변환 =====
const VALID_STATUSES: InvoiceStatus[] = ['draft', 'issued', 'sent', 'cancelled', 'failed'];

const INVOICE_TYPE_TO_TAX_TYPE: Record<string, TaxType> = {
  tax_invoice: 'taxable',
  modified: 'taxable',
  invoice: 'tax_free',
};

const ISSUE_TYPE_TO_RECEIPT_TYPE: Record<string, ReceiptType> = {
  receipt: 'receipt',
  claim: 'claim',
};

export function transformApiToFrontend(apiData: TaxInvoiceMgmtApiData): TaxInvoiceMgmtRecord {
  const isSales = apiData.direction === 'sales';
  return {
    id: String(apiData.id),
    division: isSales ? 'sales' : 'purchase',
    writeDate: apiData.issue_date || apiData.created_at?.split('T')[0] || '',
    issueDate: apiData.issue_date,
    vendorName: isSales
      ? (apiData.buyer_corp_name || '')
      : (apiData.supplier_corp_name || ''),
    vendorBusinessNumber: isSales
      ? (apiData.buyer_corp_num || '')
      : (apiData.supplier_corp_num || ''),
    taxType: INVOICE_TYPE_TO_TAX_TYPE[apiData.invoice_type || ''] || 'taxable',
    itemName: apiData.items?.[0]?.name || apiData.description || '',
    supplyAmount: Number(apiData.supply_amount) || 0,
    taxAmount: Number(apiData.tax_amount) || 0,
    totalAmount: Number(apiData.total_amount) || 0,
    receiptType: ISSUE_TYPE_TO_RECEIPT_TYPE[apiData.issue_type || ''] || 'receipt',
    documentNumber: apiData.nts_confirm_num || '',
    status: VALID_STATUSES.includes(apiData.status as InvoiceStatus)
      ? (apiData.status as InvoiceStatus)
      : 'draft',
    source: apiData.barobill_invoice_id ? 'hometax' : 'manual',
    memo: apiData.description || '',
  };
}

// ===== Frontend → API 변환 =====
export function transformFrontendToApi(data: ManualEntryFormData): Record<string, unknown> {
  const isSales = data.division === 'sales';
  return {
    direction: isSales ? 'sales' : 'purchases',
    issue_type: 'normal',
    issue_date: data.writeDate,
    // 매출: 거래처=공급받는자(buyer), 매입: 거래처=공급자(supplier)
    // DB 컬럼이 NOT NULL이므로 빈 문자열로 전송
    supplier_corp_name: isSales ? '' : data.vendorName,
    supplier_corp_num: isSales ? '' : data.vendorBusinessNumber,
    buyer_corp_name: isSales ? data.vendorName : '',
    buyer_corp_num: isSales ? data.vendorBusinessNumber : '',
    supply_amount: data.supplyAmount,
    tax_amount: data.taxAmount,
    total_amount: data.totalAmount,
    invoice_type: data.taxType === 'tax_free' ? 'invoice' : 'tax_invoice',
    description: data.memo || null,
    items: data.itemName ? [{ name: data.itemName, amount: data.supplyAmount }] : [],
  };
}

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

// ===== 요약 API → Frontend 변환 =====
const EMPTY_DIRECTION: DirectionSummary = { count: 0, supply_amount: 0, tax_amount: 0, total_amount: 0 };

export function transformSummaryApi(apiData: TaxInvoiceSummaryApiData): TaxInvoiceSummary {
  const sales = apiData.by_direction?.sales || EMPTY_DIRECTION;
  const purchases = apiData.by_direction?.purchases || EMPTY_DIRECTION;
  return {
    salesSupplyAmount: sales.supply_amount,
    salesTaxAmount: sales.tax_amount,
    salesTotalAmount: sales.total_amount,
    salesCount: sales.count,
    purchaseSupplyAmount: purchases.supply_amount,
    purchaseTaxAmount: purchases.tax_amount,
    purchaseTotalAmount: purchases.total_amount,
    purchaseCount: purchases.count,
  };
}
