import { DomainError } from './errors.js';

export type DeliveryRequestState = 'pending' | 'delivered' | 'cancelled' | 'returned';
export type WarehouseAction = 'deliver' | 'cancel' | 'return';

export interface QuantityLine {
  productCode: string;
  approved: number;
  delivered: number;
  reserved: number;
}

export function nextWarehouseState(current: DeliveryRequestState, action: WarehouseAction): DeliveryRequestState {
  if (action === 'deliver' && (current === 'pending' || current === 'returned')) return 'delivered';
  if (action === 'cancel' && (current === 'pending' || current === 'returned')) return 'cancelled';
  if (action === 'return' && current === 'delivered') return 'returned';
  throw new DomainError('این عملیات با وضعیت فعلی درخواست تحویل سازگار نیست.', 'INVALID_DELIVERY_TRANSITION', 409);
}

export function warehouseEventType(current: DeliveryRequestState, action: WarehouseAction) {
  if (action === 'deliver') return current === 'returned' ? 'redelivered' : 'delivered';
  if (action === 'cancel') return 'cancelled';
  return 'returned';
}

export function validateApprovedQuantity(quantity: number, remaining: number): void {
  if (!Number.isFinite(quantity) || quantity < 1) {
    throw new DomainError('مقدار تأییدشده باید حداقل ۱ باشد.', 'INVALID_QUANTITY');
  }
  if (quantity > remaining) {
    throw new DomainError('مقدار تأییدشده بیشتر از مقدار قابل تحویل است.', 'OVER_DELIVERY');
  }
}

export function invoiceOperationalStatus(input: {
  archived: boolean;
  hasDiscrepancy: boolean;
  totalQuantity: number;
  deliveredQuantity: number;
  hasPending: boolean;
  hasCancelled: boolean;
  hasReturned: boolean;
}): { code: string; label: string; flags: string[] } {
  const flags: string[] = [];
  if (input.hasDiscrepancy) flags.push('دارای مغایرت');
  if (input.archived) return { code: 'archived', label: 'بایگانی‌شده', flags };
  if (input.hasReturned) return { code: 'returned', label: 'برگشت از تحویل', flags };
  if (input.hasPending) return { code: 'pending', label: 'در انتظار تحویل', flags };
  if (input.totalQuantity > 0 && input.deliveredQuantity >= input.totalQuantity) {
    return { code: 'complete', label: 'تحویل کامل', flags };
  }
  if (input.deliveredQuantity > 0) return { code: 'partial', label: 'تحویل جزئی', flags };
  if (input.hasCancelled) return { code: 'cancelled', label: 'لغو تحویل', flags };
  return { code: 'not_registered', label: 'ثبت‌نشده برای خروج', flags };
}

