/**
 * Bookings API
 *
 * Booking-related API calls
 */

import { apiClient } from './client';

export interface CreateBookingRequest {
  rateQuoteId: string;
  shipper: {
    name: string;
    address: {
      street: string;
      city: string;
      postalCode: string;
      country: string;
    };
    contactName: string;
    contactEmail: string;
    contactPhone: string;
  };
  consignee: {
    name: string;
    address: {
      street: string;
      city: string;
      postalCode: string;
      country: string;
    };
    contactName: string;
    contactEmail: string;
    contactPhone: string;
  };
  containers: Array<{
    type: string;
    containerNumber?: string;
    vgm?: number;
    temperature?: number;
    sealNumber?: string;
  }>;
  cargoDescription: string;
  specialInstructions?: string;
}

export interface BookingResponse {
  id: string;
  bookingNumber: string;
  userId: string;
  organizationId: string;
  rateQuoteId: string;
  status: string;
  shipper: any;
  consignee: any;
  containers: any[];
  cargoDescription: string;
  specialInstructions?: string;
  createdAt: string;
  updatedAt: string;
}

export interface BookingListParams {
  page?: number;
  limit?: number;
  status?: string;
  search?: string;
}

export interface BookingListResponse {
  data: BookingResponse[];
  total: number;
  page: number;
  limit: number;
}

export const bookingsApi = {
  /**
   * Create a new booking
   */
  async create(data: CreateBookingRequest): Promise<BookingResponse> {
    return apiClient.post<BookingResponse>('/api/v1/bookings', data);
  },

  /**
   * Get booking by ID
   */
  async getById(id: string): Promise<BookingResponse> {
    return apiClient.get<BookingResponse>(`/api/v1/bookings/${id}`);
  },

  /**
   * List bookings with filters
   */
  async list(params?: BookingListParams): Promise<BookingListResponse> {
    const queryParams = new URLSearchParams();
    if (params?.page) queryParams.append('page', params.page.toString());
    if (params?.limit) queryParams.append('limit', params.limit.toString());
    if (params?.status) queryParams.append('status', params.status);
    if (params?.search) queryParams.append('search', params.search);

    const queryString = queryParams.toString();
    const url = `/api/v1/bookings${queryString ? `?${queryString}` : ''}`;

    return apiClient.get<BookingListResponse>(url);
  },

  /**
   * Get booking by booking number
   */
  async getByBookingNumber(bookingNumber: string): Promise<BookingResponse> {
    return apiClient.get<BookingResponse>(`/api/v1/bookings/number/${bookingNumber}`);
  },

  /**
   * Download booking PDF
   */
  async downloadPdf(id: string): Promise<Blob> {
    const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/bookings/${id}/pdf`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });

    if (!response.ok) {
      throw new Error('Failed to download PDF');
    }

    return response.blob();
  },
};
