import { useCompanyStore } from '@/stores/companyStore';

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000';

// Helper to get active company ID from store
function getActiveCompanyId(): string | null {
  return useCompanyStore.getState().activeCompany?.id ?? null;
}

/**
 * Result of document processing from AI Bookkeeper.
 */
export interface DocumentProcessingResult {
  draftId?: string;
  attachmentId?: string;
  isDuplicate: boolean;
  message?: string;
  extraction?: ExtractionResult;
  accountSuggestion?: AccountSuggestionResult;
  bankTransactionMatch?: BankTransactionMatchResult;
  suggestedLines?: SuggestedJournalLine[];
}

export interface ExtractionResult {
  vendor?: string;
  vendorCvr?: string;
  amount?: number;
  amountExVat?: number;
  vatAmount?: number;
  date?: string;
  dueDate?: string;
  invoiceNumber?: string;
  documentType?: string;
  currency?: string;
  paymentReference?: string;
  lineItems?: ExtractedLineItem[];
}

export interface ExtractedLineItem {
  description?: string;
  quantity?: number;
  unitPrice?: number;
  amount?: number;
  vatRate?: number;
}

export interface AccountSuggestionResult {
  mappedAccountId?: string;
  mappedAccountNumber?: string;
  mappedAccountName?: string;
  confidence: number;
}

export interface BankTransactionMatchResult {
  transactionId?: string;
  amount: number;
  date?: string;
  description?: string;
  counterparty?: string;
}

export interface SuggestedJournalLine {
  accountId?: string;
  accountNumber?: string;
  accountName?: string;
  debitAmount: number;
  creditAmount: number;
  vatCode?: string;
}

export interface DocumentProcessingError {
  code: string;
  message: string;
}

/**
 * Process a document using AI Bookkeeper.
 * Uploads the file, analyzes it, creates a draft, and optionally matches to a bank transaction.
 *
 * @param file The file to process
 * @param companyId Optional company ID (defaults to active company)
 * @returns Processing result including extraction, account suggestion, and bank match
 */
export async function processDocument(
  file: File,
  companyId?: string
): Promise<DocumentProcessingResult> {
  const effectiveCompanyId = companyId || getActiveCompanyId();

  if (!effectiveCompanyId) {
    throw new Error('No company selected');
  }

  const formData = new FormData();
  formData.append('document', file);

  const response = await fetch(
    `${API_BASE_URL}/api/documents/process?companyId=${encodeURIComponent(effectiveCompanyId)}`,
    {
      method: 'POST',
      body: formData,
      credentials: 'include',
    }
  );

  if (!response.ok) {
    // Try to parse error response
    try {
      const errorData = (await response.json()) as DocumentProcessingError;
      throw new DocumentProcessingApiError(
        errorData.code || 'UNKNOWN_ERROR',
        errorData.message || 'Der opstod en fejl ved behandling af dokumentet'
      );
    } catch (e) {
      if (e instanceof DocumentProcessingApiError) {
        throw e;
      }
      // Fallback error handling
      if (response.status === 401) {
        throw new DocumentProcessingApiError('NOT_AUTHENTICATED', 'Du skal vaere logget ind');
      }
      if (response.status === 403) {
        throw new DocumentProcessingApiError('FORBIDDEN', 'Du har ikke adgang til denne virksomhed');
      }
      if (response.status === 413) {
        throw new DocumentProcessingApiError('FILE_TOO_LARGE', 'Filen er for stor (maks 10MB)');
      }
      if (response.status === 503) {
        throw new DocumentProcessingApiError('AI_UNAVAILABLE', 'AI-tjenesten er midlertidigt utilgængelig');
      }
      throw new DocumentProcessingApiError('UNKNOWN_ERROR', `Serverfejl: ${response.status}`);
    }
  }

  return (await response.json()) as DocumentProcessingResult;
}

/**
 * Custom error class for document processing errors.
 */
export class DocumentProcessingApiError extends Error {
  public readonly code: string;

  constructor(code: string, message: string) {
    super(message);
    this.name = 'DocumentProcessingApiError';
    this.code = code;
  }
}

/**
 * Check if a file is valid for document processing.
 */
export function isValidDocumentFile(file: File): { valid: boolean; error?: string } {
  const allowedTypes = ['application/pdf', 'image/png', 'image/jpeg', 'image/jpg'];
  const maxSize = 10 * 1024 * 1024; // 10MB

  if (!allowedTypes.includes(file.type)) {
    return {
      valid: false,
      error: 'Kun PDF og billeder (PNG, JPG) er tilladt',
    };
  }

  if (file.size > maxSize) {
    return {
      valid: false,
      error: 'Filen er for stor (maks 10MB)',
    };
  }

  return { valid: true };
}
