import { api } from './api';
import type {
  AtemschutzUebersicht,
  AtemschutzTraeger,
  AtemschutzStats,
  CreateAtemschutzPayload,
  UpdateAtemschutzPayload,
} from '../types/atemschutz.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 atemschutzApi = {
  async getAll(): Promise<AtemschutzUebersicht[]> {
    return unwrap(
      api.get<{ success: boolean; data: AtemschutzUebersicht[] }>('/api/atemschutz')
    );
  },

  async getByUserId(userId: string): Promise<AtemschutzUebersicht | null> {
    const response = await api.get<{ success: boolean; data: AtemschutzUebersicht | null }>(
      `/api/atemschutz/user/${userId}`
    );
    return response.data?.data ?? null;
  },

  async getMyStatus(): Promise<AtemschutzUebersicht | null> {
    const response = await api.get<{ success: boolean; data: AtemschutzUebersicht | null }>(
      '/api/atemschutz/my-status'
    );
    // data can be null when the user has no atemschutz entry
    return response.data?.data ?? null;
  },

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

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

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

  async getExpiring(): Promise<any[]> {
    const response = await api.get<{ success: boolean; data: any[] }>('/api/atemschutz/expiring');
    return response.data?.data ?? [];
  },
};
