import { api } from './api';
import type {
  PersoenlicheAusruestung,
  CreatePersoenlicheAusruestungPayload,
  UpdatePersoenlicheAusruestungPayload,
  ZustandOption,
} from '../types/personalEquipment.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 personalEquipmentApi = {
  async getAll(params?: { user_id?: string; kategorie?: string; zustand?: string }): Promise<PersoenlicheAusruestung[]> {
    const qs = new URLSearchParams();
    if (params?.user_id) qs.set('user_id', params.user_id);
    if (params?.kategorie) qs.set('kategorie', params.kategorie);
    if (params?.zustand) qs.set('zustand', params.zustand);
    return unwrap(api.get(`/api/persoenliche-ausruestung?${qs.toString()}`));
  },

  async getMy(): Promise<PersoenlicheAusruestung[]> {
    return unwrap(api.get('/api/persoenliche-ausruestung/my'));
  },

  async getByUserId(userId: string): Promise<PersoenlicheAusruestung[]> {
    return unwrap(api.get(`/api/persoenliche-ausruestung/user/${userId}`));
  },

  async getById(id: string): Promise<PersoenlicheAusruestung> {
    return unwrap(api.get(`/api/persoenliche-ausruestung/${id}`));
  },

  async create(data: CreatePersoenlicheAusruestungPayload): Promise<PersoenlicheAusruestung> {
    const response = await api.post<{ success: boolean; data: PersoenlicheAusruestung }>(
      '/api/persoenliche-ausruestung',
      data,
    );
    if (response.data?.data === undefined || response.data?.data === null) {
      throw new Error('Invalid API response');
    }
    return response.data.data;
  },

  async update(id: string, data: UpdatePersoenlicheAusruestungPayload): Promise<PersoenlicheAusruestung> {
    const response = await api.patch<{ success: boolean; data: PersoenlicheAusruestung }>(
      `/api/persoenliche-ausruestung/${id}`,
      data,
    );
    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/persoenliche-ausruestung/${id}`);
  },

  async getZustandOptions(): Promise<ZustandOption[]> {
    return unwrap(api.get('/api/persoenliche-ausruestung/zustand-options'));
  },

  async updateZustandOptions(options: ZustandOption[]): Promise<ZustandOption[]> {
    return unwrap(api.put('/api/persoenliche-ausruestung/zustand-options', { options }));
  },
};
