import { api } from './api';
import type {
  FahrzeugListItem,
  FahrzeugDetail,
  FahrzeugWartungslog,
  VehicleStats,
  InspectionAlert,
  CreateFahrzeugPayload,
  UpdateFahrzeugPayload,
  UpdateStatusPayload,
  CreateWartungslogPayload,
  UpdateWartungslogPayload,
  StatusUpdateResponse,
} from '../types/vehicle.types';

async function unwrap<T>(
  promise: ReturnType<typeof api.get<{ success: boolean; data: T }>>
): Promise<T> {
  const response = await promise;
  if (response.data?.data === undefined || response.data?.data === null) {
    throw new Error('Invalid API response');
  }
  return response.data.data;
}

export const vehiclesApi = {
  async getAll(): Promise<FahrzeugListItem[]> {
    return unwrap(api.get<{ success: boolean; data: FahrzeugListItem[] }>('/api/vehicles'));
  },

  async getStats(): Promise<VehicleStats> {
    return unwrap(api.get<{ success: boolean; data: VehicleStats }>('/api/vehicles/stats'));
  },

  async getAlerts(daysAhead = 30): Promise<InspectionAlert[]> {
    return unwrap(
      api.get<{ success: boolean; data: InspectionAlert[] }>(
        `/api/vehicles/alerts?daysAhead=${daysAhead}`
      )
    );
  },

  async getById(id: string): Promise<FahrzeugDetail> {
    return unwrap(api.get<{ success: boolean; data: FahrzeugDetail }>(`/api/vehicles/${id}`));
  },

  async create(payload: CreateFahrzeugPayload): Promise<FahrzeugDetail> {
    const response = await api.post<{ success: boolean; data: FahrzeugDetail }>(
      '/api/vehicles',
      payload
    );
    if (response.data?.data === undefined || response.data?.data === null) {
      throw new Error('Invalid API response');
    }
    return response.data.data;
  },

  async update(id: string, payload: UpdateFahrzeugPayload): Promise<FahrzeugDetail> {
    const response = await api.patch<{ success: boolean; data: FahrzeugDetail }>(
      `/api/vehicles/${id}`,
      payload
    );
    if (response.data?.data === undefined || response.data?.data === null) {
      throw new Error('Invalid API response');
    }
    return response.data.data;
  },

  async delete(id: string): Promise<void> {
    await api.delete(`/api/vehicles/${id}`);
  },

  async updateStatus(id: string, payload: UpdateStatusPayload): Promise<StatusUpdateResponse> {
    const response = await api.patch<{ success: boolean; data: StatusUpdateResponse }>(
      `/api/vehicles/${id}/status`,
      payload
    );
    return response.data?.data ?? { overlappingBookings: [] };
  },

  async getWartungslog(id: string): Promise<FahrzeugWartungslog[]> {
    return unwrap(
      api.get<{ success: boolean; data: FahrzeugWartungslog[] }>(`/api/vehicles/${id}/wartung`)
    );
  },

  async addWartungslog(id: string, payload: CreateWartungslogPayload): Promise<FahrzeugWartungslog> {
    const response = await api.post<{ success: boolean; data: FahrzeugWartungslog }>(
      `/api/vehicles/${id}/wartung`,
      payload
    );
    if (response.data?.data === undefined || response.data?.data === null) {
      throw new Error('Invalid API response');
    }
    return response.data.data;
  },

  async updateWartungslog(vehicleId: string, wartungId: string, payload: UpdateWartungslogPayload): Promise<FahrzeugWartungslog> {
    const response = await api.patch<{ success: boolean; data: FahrzeugWartungslog }>(
      `/api/vehicles/${vehicleId}/wartung/${wartungId}`,
      payload
    );
    if (response.data?.data === undefined || response.data?.data === null) {
      throw new Error('Invalid API response');
    }
    return response.data.data;
  },

  async exportAlerts(): Promise<Blob> {
    const response = await api.get('/api/vehicles/alerts/export', {
      responseType: 'blob',
    });
    return response.data as Blob;
  },

  async getStatusHistory(id: string): Promise<{ alter_status: string; neuer_status: string; bemerkung?: string; geaendert_von_name?: string; erstellt_am: string }[]> {
    return unwrap(api.get(`/api/vehicles/${id}/status-history`));
  },

  async uploadWartungFile(wartungId: number, file: File): Promise<any> {
    const formData = new FormData();
    formData.append('datei', file);
    const r = await api.post(`/api/vehicles/wartung/${wartungId}/upload`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return r.data.data;
  },
};
