import { Injectable, Inject, NotFoundException } from '@nestjs/common';
import { Booking } from '../entities/booking.entity';
import { BookingRepository } from '@domain/ports/out/booking.repository';
import { RateQuoteRepository } from '@domain/ports/out/rate-quote.repository';
import { BOOKING_REPOSITORY } from '@domain/ports/out/booking.repository';
import { RATE_QUOTE_REPOSITORY } from '@domain/ports/out/rate-quote.repository';
import { v4 as uuidv4 } from 'uuid';

export interface CreateBookingInput {
  rateQuoteId: string;
  shipper: any;
  consignee: any;
  cargoDescription: string;
  containers: any[];
  specialInstructions?: string;
}

@Injectable()
export class BookingService {
  constructor(
    @Inject(BOOKING_REPOSITORY)
    private readonly bookingRepository: BookingRepository,

    @Inject(RATE_QUOTE_REPOSITORY)
    private readonly rateQuoteRepository: RateQuoteRepository
  ) {}

  /**
   * Create a new booking
   */
  async createBooking(input: CreateBookingInput): Promise<Booking> {
    // Validate rate quote exists
    const rateQuote = await this.rateQuoteRepository.findById(input.rateQuoteId);
    if (!rateQuote) {
      throw new NotFoundException(`Rate quote ${input.rateQuoteId} not found`);
    }

    // TODO: Get userId and organizationId from context
    const userId = 'temp-user-id';
    const organizationId = 'temp-org-id';

    // Create booking entity
    const booking = Booking.create({
      id: uuidv4(),
      userId,
      organizationId,
      rateQuoteId: input.rateQuoteId,
      shipper: input.shipper,
      consignee: input.consignee,
      cargoDescription: input.cargoDescription,
      containers: input.containers.map(c => ({
        id: uuidv4(),
        type: c.type,
        containerNumber: c.containerNumber,
        vgm: c.vgm,
        temperature: c.temperature,
        sealNumber: c.sealNumber,
      })),
      specialInstructions: input.specialInstructions,
    });

    // Persist booking
    return this.bookingRepository.save(booking);
  }
}
