import { api } from './api';
import type {
  AusruestungListItem,
  AusruestungDetail,
  AusruestungWartungslog,
  AusruestungKategorie,
  EquipmentStats,
  VehicleEquipmentWarning,
  CreateAusruestungPayload,
  UpdateAusruestungPayload,
  UpdateAusruestungStatusPayload,
  CreateAusruestungWartungslogPayload,
  UpdateAusruestungWartungslogPayload,
} from '../types/equipment.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 equipmentApi = {
  async getAll(): Promise<AusruestungListItem[]> {
    return unwrap(api.get<{ success: boolean; data: AusruestungListItem[] }>('/api/equipment'));
  },

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

  async getByVehicle(fahrzeugId: string): Promise<AusruestungListItem[]> {
    return unwrap(
      api.get<{ success: boolean; data: AusruestungListItem[] }>(
        `/api/equipment/vehicle/${fahrzeugId}`
      )
    );
  },

  async getCategories(): Promise<AusruestungKategorie[]> {
    return unwrap(
      api.get<{ success: boolean; data: AusruestungKategorie[] }>('/api/equipment/categories')
    );
  },

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

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

  async getVehicleWarnings(): Promise<VehicleEquipmentWarning[]> {
    return unwrap(
      api.get<{ success: boolean; data: VehicleEquipmentWarning[] }>(
        '/api/equipment/vehicle-warnings'
      )
    );
  },

  async create(payload: CreateAusruestungPayload): Promise<AusruestungDetail> {
    const response = await api.post<{ success: boolean; data: AusruestungDetail }>(
      '/api/equipment',
      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: UpdateAusruestungPayload): Promise<AusruestungDetail> {
    const response = await api.patch<{ success: boolean; data: AusruestungDetail }>(
      `/api/equipment/${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/equipment/${id}`);
  },

  async updateStatus(id: string, payload: UpdateAusruestungStatusPayload): Promise<void> {
    await api.patch(`/api/equipment/${id}/status`, payload);
  },

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

  async getStatusHistory(id: string): Promise<Array<{
    alter_status: string;
    neuer_status: string;
    bemerkung?: string;
    geaendert_von_name?: string;
    erstellt_am: string;
  }>> {
    const response = await api.get<{ success: boolean; data: any[] }>(
      `/api/equipment/${id}/status-history`
    );
    return response.data.data ?? [];
  },

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

  async createCategory(payload: { name: string; kurzname: string; sortierung?: number; motorisiert?: boolean }): Promise<AusruestungKategorie> {
    const response = await api.post<{ success: boolean; data: AusruestungKategorie }>(
      '/api/equipment/categories',
      payload
    );
    if (response.data?.data === undefined || response.data?.data === null) {
      throw new Error('Invalid API response');
    }
    return response.data.data;
  },

  async updateCategory(id: string, payload: { name?: string; kurzname?: string; sortierung?: number; motorisiert?: boolean }): Promise<AusruestungKategorie> {
    const response = await api.patch<{ success: boolean; data: AusruestungKategorie }>(
      `/api/equipment/categories/${id}`,
      payload
    );
    if (response.data?.data === undefined || response.data?.data === null) {
      throw new Error('Invalid API response');
    }
    return response.data.data;
  },

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