import { api as client } from '../auth/http';
import { unwrap } from '@/utils/endpoint';
import { URL_CONSTANTS } from '@/constants/URLS';
import type {
  CreateTrainSchedulePayload,
  EligibleContainerBookingsResponse,
  LocomotiveRecord,
  TrainScheduleDetail,
  TrainScheduleFilters,
  TrainScheduleListItem,
  TrainSchedulePreviewPayload,
  TrainSchedulePreviewResponse,
  YardOption,
} from '@/types/trainScheduling';

interface BookingReferenceDataResponse {
  yard?: Array<YardOption & { label?: string }>;
}

export const trainSchedulingService = {
  getEligibleBookings: async (
    filters?: TrainScheduleFilters,
  ): Promise<EligibleContainerBookingsResponse> => {
    const response = await client.get<EligibleContainerBookingsResponse>(
      URL_CONSTANTS.TRAIN_SCHEDULING.ELIGIBLE_BOOKINGS,
      { params: filters },
    );
    return unwrap(response.data);
  },

  preview: async (
    payload: TrainSchedulePreviewPayload,
  ): Promise<TrainSchedulePreviewResponse> => {
    const response = await client.post<TrainSchedulePreviewResponse>(
      URL_CONSTANTS.TRAIN_SCHEDULING.PREVIEW,
      payload,
    );
    return unwrap(response.data);
  },

  createSchedule: async (
    payload: CreateTrainSchedulePayload,
  ): Promise<TrainScheduleDetail> => {
    const response = await client.post<TrainScheduleDetail>(
      URL_CONSTANTS.TRAIN_SCHEDULING.SCHEDULES,
      payload,
    );
    return unwrap(response.data);
  },

  listSchedules: async (): Promise<TrainScheduleListItem[]> => {
    const response = await client.get<TrainScheduleListItem[]>(
      URL_CONSTANTS.TRAIN_SCHEDULING.SCHEDULES,
    );
    return unwrap(response.data);
  },

  getScheduleById: async (id: string): Promise<TrainScheduleDetail> => {
    const response = await client.get<TrainScheduleDetail>(
      URL_CONSTANTS.TRAIN_SCHEDULING.SCHEDULE_BY_ID(id),
    );
    return unwrap(response.data);
  },

  cancelSchedule: async (id: string): Promise<TrainScheduleDetail> => {
    const response = await client.post<TrainScheduleDetail>(
      URL_CONSTANTS.TRAIN_SCHEDULING.CANCEL_SCHEDULE(id),
      {},
    );
    return unwrap(response.data);
  },

  getAvailableLocomotives: async (): Promise<LocomotiveRecord[]> => {
    const response = await client.get<LocomotiveRecord[]>(URL_CONSTANTS.LOCOMOTIVES.BASE, {
      params: { status: 'AVAILABLE' },
    });
    return unwrap(response.data);
  },

  getStations: async (): Promise<YardOption[]> => {
    const response = await client.get<BookingReferenceDataResponse>(
      URL_CONSTANTS.BOOKINGS.REFERENCE_DATA,
    );
    const data = unwrap(response.data);
    return (data.yard ?? []).map((yard) => ({
      id: yard.id,
      name: yard.name ?? yard.label ?? yard.code,
      code: yard.code,
      country: yard.country,
    }));
  },
};
