import { Injectable } from '@nestjs/common';

import { Booking } from '../modules/bookings/entities/booking.entity';
import { ServiceType } from '../modules/rule-engine/entities/service-type.entity';
import { CargoType } from '../modules/rule-engine/entities/cargo-type.entity';

@Injectable()
export class ContractTemplateResolver {
  resolve(booking: Booking): string {
    const dir =
      booking.tradeDirection === 'IMPORT'
        ? 'IMP'
        : booking.tradeDirection === 'EXPORT'
          ? 'EXP'
          : 'DOM';

    let freight = booking.freightType === 'BULK' ? 'BULK' : 'CON';
    const cargoCode = (booking.cargoType as CargoType | undefined)?.code ?? '';
    if (cargoCode.startsWith('BREAK_BULK')) {
      freight = 'BULK';
    }

    const currency = booking.paymentCurrency === 'ETB' ? 'ETB' : 'USD';
    const service = this.resolveServiceScope(booking.serviceType);

    return `${dir}_${freight}_${currency}_${service}`;
  }

  private resolveServiceScope(
    serviceType?: ServiceType | null,
  ): 'TRANSPORT_ONLY' | 'FORWARDING' {
    if (!serviceType) return 'TRANSPORT_ONLY';
    const code = (serviceType.code ?? '').toUpperCase();
    if (
      serviceType.includesFirstMile ||
      serviceType.includesLastMile ||
      code.includes('FORWARD')
    ) {
      return 'FORWARDING';
    }
    return 'TRANSPORT_ONLY';
  }
}
