// VAT (Moms) Types for Danish SKAT Compliance

import type { VATPeriodicitet } from './periods';

// =====================================================
// SKAT VAT CODES (Momskoder)
// =====================================================

/**
 * VAT codes used in Danish bookkeeping
 */
export type VATCode =
  | 'S25'         // Salgsmoms 25% (udgaaende moms)
  | 'K25'         // Koebsmoms 25% (indgaaende moms)
  | 'EU_VARE'     // EU-varekoeb (reverse charge)
  | 'EU_YDELSE'   // EU-ydelseskoeb (reverse charge)
  | 'MOMSFRI'     // Momsfritaget (healthcare, education, etc.)
  | 'EKSPORT'     // Eksport (0%)
  | 'NONE';       // Ingen moms

/**
 * VAT code type classification
 */
export type VATCodeType =
  | 'output'        // Udgaaende moms (salg)
  | 'input'         // Indgaaende moms (koeb)
  | 'reverse_charge' // Omvendt betalingspligt
  | 'exempt'        // Momsfritaget
  | 'none';         // Ingen moms

/**
 * VAT code configuration with calculation rules
 */
export interface VATCodeConfig {
  code: VATCode;
  nameDanish: string;
  nameEnglish: string;
  rate: number;              // VAT rate (0.25 for 25%)
  type: VATCodeType;
  affectsBoxes: {
    vatBox?: VATBoxId;       // Which VAT box this affects
    basisBox?: BasisBoxId;   // Which basis/turnover box this affects
  };
  reverseCharge: boolean;    // Is this reverse charge VAT?
  deductible: boolean;       // Is this VAT deductible?
  description: string;       // Danish description for UI
}

// =====================================================
// SKAT VAT BOXES (Rubrikker)
// =====================================================

/**
 * SKAT VAT Box identifiers
 * Rubrik A-D: VAT amounts (momsbeloeb)
 * Rubrik 1-4: Turnover/basis amounts (omsaetning/grundlag)
 */
export type VATBoxId = 'A' | 'B' | 'C' | 'D';
export type BasisBoxId = '1' | '2' | '3' | '4';

/**
 * SKAT VAT Box (Rubrik) definition
 */
export interface SKATVATBox {
  id: VATBoxId | BasisBoxId;
  type: 'vat' | 'basis';
  nameDanish: string;
  nameEnglish: string;
  description: string;
  skippable: boolean;        // Can be omitted if zero
  isDeductible: boolean;     // Is this a deductible amount?
}

/**
 * Calculated VAT box with amount
 */
export interface CalculatedVATBox extends SKATVATBox {
  amount: number;
  basis?: number;            // For VAT boxes, the underlying basis amount
  transactionCount: number;  // Number of transactions contributing
  transactionIds: string[];  // IDs of contributing transactions
}

// =====================================================
// VAT REPORT
// =====================================================

/**
 * VAT report status
 */
export type VATReportStatus =
  | 'future'           // Period hasn't started yet
  | 'open'             // Period is open for transactions
  | 'closed'           // Period closed, not yet reported
  | 'draft'            // Report drafted but not submitted
  | 'submitted'        // Submitted to SKAT
  | 'accepted'         // Accepted by SKAT
  | 'rejected'         // Rejected by SKAT
  | 'corrected';       // Correction submitted

/**
 * VAT Report Period (matches VATPeriod in periods.ts but specific to reports)
 */
export interface VATReportPeriod {
  id: string;
  companyId: string;
  periodicitet: VATPeriodicitet;
  year: number;
  periodNumber: number;
  startDate: string;
  endDate: string;
  deadline: string;
  status: VATReportStatus;
}

/**
 * Complete VAT report for a period
 */
export interface VATReport {
  id: string;
  companyId: string;
  period: VATReportPeriod;

  // SKAT boxes with calculated amounts
  boxes: {
    // VAT amounts (Momsbeloeb)
    A: CalculatedVATBox;  // Salgsmoms (udgaaende moms)
    B: CalculatedVATBox;  // Koebsmoms (indgaaende moms - fradrag)
    C: CalculatedVATBox;  // EU-varekoeb moms
    D: CalculatedVATBox;  // Ydelseskoeb fra udland moms

    // Basis/turnover amounts (Omsaetning)
    '1': CalculatedVATBox;  // Salg med moms (momsgrundlag)
    '2': CalculatedVATBox;  // Salg uden moms (momsfrit/eksport)
    '3': CalculatedVATBox;  // EU-varekoeb
    '4': CalculatedVATBox;  // Ydelseskoeb fra udland
  };

  // Summary calculations
  totalOutputVAT: number;        // A + C + D
  totalInputVAT: number;         // B (fradragsberettiget)
  netVAT: number;                // totalOutputVAT - totalInputVAT

  // Energy duty refunds (Afgiftsgodtgoerelse) - optional
  energyDuties?: {
    oilGas: number;              // Olie- og flaskegasafgift
    electricity: number;          // Elafgift
    naturalGas: number;           // Naturgas- og bygasafgift
    coal: number;                 // Kulafgift
    co2: number;                  // CO2-afgift
  };

  // Metadata
  status: VATReportStatus;
  createdAt: string;
  updatedAt: string;
  submittedAt?: string;
  submittedBy?: string;
  skatReferenceNumber?: string;  // Reference from SKAT

  // Audit trail
  adjustments: VATAdjustment[];
  history: VATReportHistory[];
}

/**
 * VAT adjustment entry (for corrections)
 */
export interface VATAdjustment {
  id: string;
  reportId: string;
  boxId: VATBoxId | BasisBoxId;
  previousAmount: number;
  newAmount: number;
  reason: string;
  adjustedAt: string;
  adjustedBy: string;
}

/**
 * VAT report history entry
 */
export interface VATReportHistory {
  id: string;
  action: 'created' | 'calculated' | 'adjusted' | 'submitted' | 'accepted' | 'rejected' | 'corrected';
  timestamp: string;
  userId: string;
  details?: string;
}

// =====================================================
// VAT CALCULATION
// =====================================================

/**
 * Transaction line with VAT information for calculation
 */
export interface VATTransactionLine {
  transactionId: string;
  transactionLineId: string;
  transactionNumber: string;
  transactionDate: string;
  accountId: string;
  accountNumber: string;
  accountName: string;
  description: string;
  debit: number;
  credit: number;
  netAmount: number;           // Amount excluding VAT
  vatCode: VATCode;
  vatAmount: number;           // Calculated VAT amount
  vatRate: number;             // Applied VAT rate
  isReverseCharge: boolean;
}

/**
 * VAT calculation result
 */
export interface VATCalculationResult {
  period: VATReportPeriod;
  transactions: VATTransactionLine[];
  boxes: Record<VATBoxId | BasisBoxId, {
    amount: number;
    transactionCount: number;
    transactionIds: string[];
  }>;
  summary: {
    totalOutputVAT: number;
    totalInputVAT: number;
    netVAT: number;
  };
  warnings: VATCalculationWarning[];
  errors: VATCalculationError[];
}

export interface VATCalculationWarning {
  type: 'missing_vat_code' | 'unusual_amount' | 'period_mismatch' | 'account_mismatch';
  message: string;
  messageDanish: string;
  transactionId?: string;
  severity: 'low' | 'medium' | 'high';
}

export interface VATCalculationError {
  type: 'invalid_vat_code' | 'calculation_error' | 'data_integrity';
  message: string;
  messageDanish: string;
  transactionId?: string;
}

// =====================================================
// SKAT EXPORT FORMAT
// =====================================================

/**
 * SKAT CSV export format
 */
export interface SKATExportCSV {
  cvr: string;
  periode: string;           // Format: YYYYMM or YYYYQQ
  rubrikA: number;
  rubrikB: number;
  rubrikC: number;
  rubrikD: number;
  felt1: number;
  felt2: number;
  felt3: number;
  felt4: number;
}

/**
 * SKAT XML export format (for API submission)
 */
export interface SKATExportXML {
  version: string;
  cvr: string;
  periodeStart: string;
  periodeSlut: string;
  angivelse: {
    salgsmoms: number;       // Rubrik A
    koebsmoms: number;       // Rubrik B
    euVarekoebMoms: number;  // Rubrik C
    ydelseskoebMoms: number; // Rubrik D
    salgMedMoms: number;     // Felt 1
    salgUdenMoms: number;    // Felt 2
    euVarekoeb: number;      // Felt 3
    ydelseskoeb: number;     // Felt 4
  };
  afgifter?: {
    olie: number;
    el: number;
    naturgas: number;
    kul: number;
    co2: number;
  };
}

// =====================================================
// SUBMISSION TRACKING
// =====================================================

/**
 * VAT submission record
 */
export interface VATSubmission {
  id: string;
  reportId: string;
  companyId: string;
  period: VATReportPeriod;

  // Submission details
  submittedAt: string;
  submittedBy: string;
  method: 'manual' | 'api';  // Manual upload or API

  // SKAT response
  skatStatus: 'pending' | 'accepted' | 'rejected';
  skatReferenceNumber?: string;
  skatResponseAt?: string;
  skatErrorMessage?: string;

  // Amounts submitted
  submittedAmounts: {
    boxA: number;
    boxB: number;
    boxC: number;
    boxD: number;
    basis1: number;
    basis2: number;
    basis3: number;
    basis4: number;
    netVAT: number;
  };

  // Files
  exportFile?: {
    type: 'csv' | 'xml';
    filename: string;
    url: string;
  };
}

// =====================================================
// PERIODICITET CONFIG
// =====================================================

/**
 * VAT period configuration per type
 */
export interface VATPeriodicitetConfig {
  type: VATPeriodicitet;
  nameDanish: string;
  nameEnglish: string;
  deadlineDaysAfterPeriod: number; // Days after period end for deadline
  periodsPerYear: number;
  threshold?: {
    min?: number;  // Minimum annual revenue
    max?: number;  // Maximum annual revenue
  };
}
