import type { PurchaseOrderDocument, PurchaseOrderPaymentMethod } from '@/lib/types';
import type { PurchaseCreateCommand } from '../domain/purchase.model';

export function mapPurchaseCreateDtoToCommand(dto: any, defaultBaseCurrency: string): PurchaseCreateCommand {
  const normalizedDocuments: PurchaseOrderDocument[] = (dto.documents || [])
    .map((doc: any) => ({
      id: String(doc.id || '').trim(),
      name: String(doc.name || '').trim(),
      filePath: String(doc.filePath || '').trim(),
      mimeType: doc.mimeType ? String(doc.mimeType).trim() : undefined,
      size: typeof doc.size === 'number' ? doc.size : undefined,
      uploadedAt: String(doc.uploadedAt || '').trim(),
      uploadedBy: doc.uploadedBy ? String(doc.uploadedBy).trim() : undefined,
    }))
    .filter((doc) => doc.id && doc.name && doc.filePath && doc.uploadedAt);

  const baseCurrencyCode = String(dto.baseCurrencyCode || defaultBaseCurrency || 'USD');
  const currencyCode = String(dto.currencyCode || baseCurrencyCode);
  const exchangeRate = currencyCode === baseCurrencyCode ? 1 : Number(dto.exchangeRate || 1);

  return {
    supplierId: String(dto.supplierId || ''),
    supplierName: String(dto.supplierName || ''),
    supplierInvoiceNumber: String(dto.supplierInvoiceNumber || '').trim() || undefined,
    supplierInvoiceDate: String(dto.supplierInvoiceDate || '').trim() || undefined,
    warehouseId: String(dto.warehouseId || '').trim() || undefined,
    realEstateLinkMode: (String(dto.realEstateLinkMode || 'none').trim() as 'none' | 'order' | 'line-items') || 'none',
    realEstateProjectId: String(dto.realEstateProjectId || '').trim() || undefined,
    realEstateProjectName: String(dto.realEstateProjectName || '').trim() || undefined,
    realEstateScope: (String(dto.realEstateScope || 'project').trim() as 'project' | 'floor' | 'part') || 'project',
    realEstateFloorLabel: String(dto.realEstateFloorLabel || '').trim() || undefined,
    realEstatePartLabel: String(dto.realEstatePartLabel || '').trim() || undefined,
    realEstateAllocationMethod: ((String(dto.realEstateAllocationMethod || 'area').trim() || 'area') as 'area' | 'sale-value' | 'manual-share'),
    allowDuplicateInvoice: Boolean(dto.allowDuplicateInvoice),
    notes: String(dto.notes || '').trim() || undefined,
    documents: normalizedDocuments,
    items: Array.isArray(dto.items) ? dto.items : [],
    taxMethod: dto.taxMethod,
    postingStatus: dto.postingType === 'posted' ? 'posted' : dto.postingType,
    purchaseTransferCreationMode:
      dto.purchaseTransferCreationMode === 'direct_internal_transfer' || dto.purchaseTransferCreationMode === 'work_task' || dto.purchaseTransferCreationMode === 'none'
        ? dto.purchaseTransferCreationMode
        : undefined,
    documentType: (dto.documentType === 'shipment' || dto.documentType === 'tax_invoice') ? dto.documentType : 'tax_invoice',
    linkedShipmentIds: Array.isArray(dto.linkedShipmentIds) ? dto.linkedShipmentIds.map(String) : [],
    invoiceTaxRate: Number(dto.invoiceTaxRate || 0),
    invoiceDiscountPercent: Number(dto.invoiceDiscountPercent || 0),
    invoiceDiscountAmount: Number(dto.invoiceDiscountAmount || 0),
    amountPaid: Number(dto.amountPaid || 0),
    paymentMethods: (Array.isArray(dto.paymentMethods) ? dto.paymentMethods : []) as PurchaseOrderPaymentMethod[],
    currencyCode,
    baseCurrencyCode,
    exchangeRate,
    rateDate: String(dto.rateDate || new Date().toISOString()),
    rateSource: String(dto.rateSource || 'manual') || 'manual',
    isAutoRate: dto.isAutoRate ?? true,
  };
}
