/**
 * RateQuote ORM Mapper
 *
 * Maps between RateQuote domain entity and RateQuoteOrmEntity
 */

import { RateQuote, RateQuoteProps } from '@domain/entities/rate-quote.entity';
import { RateQuoteOrmEntity } from '../entities/rate-quote.orm-entity';

export class RateQuoteOrmMapper {
  /**
   * Map domain entity to ORM entity
   */
  static toOrm(domain: RateQuote): RateQuoteOrmEntity {
    const orm = new RateQuoteOrmEntity();
    const props = domain.toObject();

    orm.id = props.id;
    orm.carrierId = props.carrierId;
    orm.carrierName = props.carrierName;
    orm.carrierCode = props.carrierCode;
    orm.originCode = props.origin.code;
    orm.originName = props.origin.name;
    orm.originCountry = props.origin.country;
    orm.destinationCode = props.destination.code;
    orm.destinationName = props.destination.name;
    orm.destinationCountry = props.destination.country;
    orm.baseFreight = props.pricing.baseFreight;
    orm.surcharges = props.pricing.surcharges;
    orm.totalAmount = props.pricing.totalAmount;
    orm.currency = props.pricing.currency;
    orm.containerType = props.containerType;
    orm.mode = props.mode;
    orm.etd = props.etd;
    orm.eta = props.eta;
    orm.transitDays = props.transitDays;
    orm.route = props.route;
    orm.availability = props.availability;
    orm.frequency = props.frequency;
    orm.vesselType = props.vesselType || null;
    orm.co2EmissionsKg = props.co2EmissionsKg || null;
    orm.validUntil = props.validUntil;
    orm.createdAt = props.createdAt;
    orm.updatedAt = props.updatedAt;

    return orm;
  }

  /**
   * Map ORM entity to domain entity
   */
  static toDomain(orm: RateQuoteOrmEntity): RateQuote {
    const props: RateQuoteProps = {
      id: orm.id,
      carrierId: orm.carrierId,
      carrierName: orm.carrierName,
      carrierCode: orm.carrierCode,
      origin: {
        code: orm.originCode,
        name: orm.originName,
        country: orm.originCountry,
      },
      destination: {
        code: orm.destinationCode,
        name: orm.destinationName,
        country: orm.destinationCountry,
      },
      pricing: {
        baseFreight: Number(orm.baseFreight),
        surcharges: orm.surcharges || [],
        totalAmount: Number(orm.totalAmount),
        currency: orm.currency,
      },
      containerType: orm.containerType,
      mode: orm.mode as any,
      etd: orm.etd,
      eta: orm.eta,
      transitDays: orm.transitDays,
      route: orm.route || [],
      availability: orm.availability,
      frequency: orm.frequency,
      vesselType: orm.vesselType || undefined,
      co2EmissionsKg: orm.co2EmissionsKg || undefined,
      validUntil: orm.validUntil,
      createdAt: orm.createdAt,
      updatedAt: orm.updatedAt,
    };

    return RateQuote.fromPersistence(props);
  }

  /**
   * Map array of ORM entities to domain entities
   */
  static toDomainMany(orms: RateQuoteOrmEntity[]): RateQuote[] {
    return orms.map(orm => this.toDomain(orm));
  }
}
