import { ApiAsnDto, ApiItemDto, ApiOrderDto } from '@wms/shared';
import { DomainEvent } from '@/common/events/event-bus.service';

/**
 * ERP adapters translate between an external system's message format and the
 * WMS canonical payloads (the same DTOs the public API accepts). Adding an ERP
 * means implementing this interface and registering it in ErpAdapterRegistry.
 */
export type NormalizedInbound =
  | { kind: 'ITEMS'; storerCode?: string; items: ApiItemDto[]; externalId?: string }
  | { kind: 'ASN'; asn: ApiAsnDto; externalId?: string }
  | { kind: 'ORDER'; order: ApiOrderDto; externalId?: string };

export interface OutboundErpMessage {
  messageType: string; // e.g. SAP_GRN (WMMBXY), SAP_PGI, ORDER_STATUS
  externalId?: string;
  payload: Record<string, unknown>;
  rawPayload?: string; // formatted text (xml) when the ERP expects a document
}

export interface ErpAdapter {
  readonly type: string; // matches ConnectorType
  /** Parse an inbound document (xml / json / csv text) into canonical messages. */
  parseInbound(raw: string, config: Record<string, unknown>): NormalizedInbound[];
  /** Build the outbound message for a domain event, or null when the event is not relevant. */
  formatOutbound(event: DomainEvent, context: OutboundContext, config: Record<string, unknown>): OutboundErpMessage | null;
}

export interface OutboundContext {
  storerCode?: string;
  warehouseCode?: string;
  /** Rich data the formatter may need (ASN with lines, order with lines) */
  document?: Record<string, unknown>;
}
