import { apiClient } from './client';

export interface CreateBookingPayload {
  trip_id: number | string;
  seat_id: number | string;
  passenger_name: string;
  passenger_phone: string;
  passenger_email?: string;
  passenger_cni?: string;
  payment_method?: string;
  total_amount?: number;
  pickup_branch_id?: number;
  dropoff_branch_id?: number;
  pickup_stop_id?: number;
  dropoff_stop_id?: number;
}

export interface BookingResponse {
  status: string;
  message?: string;
  data?: any;
  booking?: any;
  booking_ref?: string;
}

export const BookingApi = {
  /**
   * Submit a new passenger booking request to the backend.
   */
  async createBooking(payload: CreateBookingPayload): Promise<any> {
    const res = await apiClient.post<BookingResponse>('/bookings', payload);
    if (!res.ok) {
      const errorMsg =
        (res.data as any)?.message ||
        (res.data as any)?.error ||
        'Failed to submit booking request.';
      throw new Error(errorMsg);
    }
    return res.data?.data || res.data?.booking || res.data;
  },

  /**
   * Fetch details of an existing booking by booking reference.
   */
  async getBooking(bookingRef: string): Promise<any> {
    const res = await apiClient.get<any>(`/bookings/${bookingRef}`);
    if (!res.ok) {
      throw new Error((res.data as any)?.message || 'Booking not found');
    }
    return res.data?.data || res.data;
  },

  /**
   * Confirm booking payment and retrieve issued ticket.
   */
  async confirmBooking(bookingRef: string): Promise<any> {
    const res = await apiClient.post<any>(`/bookings/${bookingRef}/confirm`);
    if (!res.ok) {
      throw new Error((res.data as any)?.message || 'Failed to confirm booking');
    }
    return res.data?.data || res.data;
  },
};

export default BookingApi;

