import { client } from "@/utils/api";

export interface InventoryFilter {
  bookingId?: string;
}

export interface WarehouseInventoryItem {
  id: string;
  bookingId: string | null;
  warehouseId: string;
  yardId: string;
  zoneId: string;
  status: string;
  arrivedAt: string | null;
  warehouse?: {
    id: string;
    name: string;
    code: string;
  } | null;
  yard?: {
    id: string;
    name: string;
    code: string;
  } | null;
  zone?: {
    id: string;
    name: string;
    code: string;
  } | null;
}

export interface BookingScheduleView {
  schedule: {
    status: string;
    scheduledDepartureDate: string | null;
    scheduledArrivalDate: string | null;
  } | null;
  wagon?: {
    wagonNumber: string | null;
    sequenceNo: number | null;
  } | null;
}

export interface BookingHandover {
  id: string;
  bookingId: string;
  truckAssignmentId?: string | null;
  edrAssignmentId?: string | null;
  truckPlate?: string | null;
  mileType: 'SELF_HAUL' | 'EDR_LAST_MILE';
  reference: string;
  generatedAt: string;
  signedAt?: string | null;
  signerName?: string | null;
  signedByUserId?: string | null;
  signatureImageUrl?: string | null;
  deliveredAt?: string | null;
}

export const warehouseService = {
  listInventory: async (filter?: InventoryFilter): Promise<WarehouseInventoryItem[]> => {
    const { data } = await client.get("/warehouse-inventory", {
      params: filter,
    });
    return data?.data ?? data ?? [];
  },

  /** Customer-safe location endpoint — the plain list is staff-only (403 for portal users). */
  bookingLocation: async (bookingId: string): Promise<WarehouseInventoryItem[]> => {
    const { data } = await client.get(`/warehouse-inventory/bookings/${bookingId}/location`);
    return data?.data ?? data ?? [];
  },

  bookingSchedule: async (bookingId: string): Promise<BookingScheduleView> => {
    const { data } = await client.get(`/warehouse-inventory/booking-schedule/${bookingId}`);
    return data?.data ?? data ?? { schedule: null, wagon: null };
  },

  bookingHandovers: async (bookingId: string): Promise<BookingHandover[]> => {
    const { data } = await client.get(`/warehouse-inventory/bookings/${bookingId}/handovers`);
    return data?.data ?? data ?? [];
  },
};
