import { api } from './api';
import type {
  Lieferant,
  LieferantFormData,
  Bestellung,
  BestellungFormData,
  BestellungDetailResponse,
  Bestellposition,
  BestellpositionFormData,
  BestellungDatei,
  BestellungErinnerung,
  ErinnerungFormData,
  BestellungHistorie,
} from '../types/bestellung.types';
import type { AusruestungArtikel } from '../types/ausruestungsanfrage.types';

export const bestellungApi = {
  // ── Vendors ──
  getVendors: async (): Promise<Lieferant[]> => {
    const r = await api.get('/api/bestellungen/vendors');
    return r.data.data;
  },
  getVendor: async (id: number): Promise<Lieferant> => {
    const r = await api.get(`/api/bestellungen/vendors/${id}`);
    return r.data.data;
  },
  createVendor: async (data: LieferantFormData): Promise<Lieferant> => {
    const r = await api.post('/api/bestellungen/vendors', data);
    return r.data.data;
  },
  updateVendor: async (id: number, data: LieferantFormData): Promise<Lieferant> => {
    const r = await api.patch(`/api/bestellungen/vendors/${id}`, data);
    return r.data.data;
  },
  deleteVendor: async (id: number): Promise<void> => {
    await api.delete(`/api/bestellungen/vendors/${id}`);
  },

  // ── Orders ──
  getOrders: async (filters?: { status?: string; lieferant_id?: number }): Promise<Bestellung[]> => {
    const params = new URLSearchParams();
    if (filters?.status) params.set('status', filters.status);
    if (filters?.lieferant_id) params.set('lieferant_id', String(filters.lieferant_id));
    const r = await api.get(`/api/bestellungen?${params.toString()}`);
    return r.data.data;
  },
  getOrder: async (id: number): Promise<BestellungDetailResponse> => {
    const r = await api.get(`/api/bestellungen/${id}`);
    return r.data.data;
  },
  createOrder: async (data: BestellungFormData): Promise<Bestellung> => {
    const r = await api.post('/api/bestellungen', data);
    return r.data.data;
  },
  updateOrder: async (id: number, data: Partial<BestellungFormData>): Promise<Bestellung> => {
    const r = await api.patch(`/api/bestellungen/${id}`, data);
    return r.data.data;
  },
  deleteOrder: async (id: number): Promise<void> => {
    await api.delete(`/api/bestellungen/${id}`);
  },
  updateStatus: async (id: number, status: string, force?: boolean): Promise<Bestellung> => {
    const r = await api.patch(`/api/bestellungen/${id}/status`, { status, force: force || undefined });
    return r.data.data;
  },

  // ── Line Items ──
  addLineItem: async (orderId: number, data: BestellpositionFormData): Promise<Bestellposition> => {
    const r = await api.post(`/api/bestellungen/${orderId}/items`, data);
    return r.data.data;
  },
  updateLineItem: async (itemId: number, data: Partial<BestellpositionFormData>): Promise<Bestellposition> => {
    const r = await api.patch(`/api/bestellungen/items/${itemId}`, data);
    return r.data.data;
  },
  deleteLineItem: async (itemId: number): Promise<void> => {
    await api.delete(`/api/bestellungen/items/${itemId}`);
  },
  updateReceivedQty: async (itemId: number, menge: number): Promise<Bestellposition> => {
    const r = await api.patch(`/api/bestellungen/items/${itemId}/received`, { menge });
    return r.data.data;
  },

  // ── Files ──
  uploadFile: async (orderId: number, file: File): Promise<BestellungDatei> => {
    const formData = new FormData();
    formData.append('datei', file);
    const r = await api.post(`/api/bestellungen/${orderId}/files`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return r.data.data;
  },
  deleteFile: async (fileId: number): Promise<void> => {
    await api.delete(`/api/bestellungen/files/${fileId}`);
  },
  getFiles: async (orderId: number): Promise<BestellungDatei[]> => {
    const r = await api.get(`/api/bestellungen/${orderId}/files`);
    return r.data.data;
  },

  // ── Reminders ──
  addReminder: async (orderId: number, data: ErinnerungFormData): Promise<BestellungErinnerung> => {
    const r = await api.post(`/api/bestellungen/${orderId}/reminders`, data);
    return r.data.data;
  },
  markReminderDone: async (reminderId: number): Promise<void> => {
    await api.patch(`/api/bestellungen/reminders/${reminderId}`, { erledigt: true });
  },
  deleteReminder: async (reminderId: number): Promise<void> => {
    await api.delete(`/api/bestellungen/reminders/${reminderId}`);
  },

  // ── History ──
  getHistory: async (orderId: number): Promise<BestellungHistorie[]> => {
    const r = await api.get(`/api/bestellungen/${orderId}/history`);
    return r.data.data;
  },

  // ── Users with order permission ──
  getOrderUsers: async (): Promise<Array<{ id: string; name: string }>> => {
    const r = await api.get('/api/permissions/users-with', { params: { permission: 'bestellungen:create' } });
    return r.data.data;
  },

  // ── All members (for "Für Mitglied" selector) ──
  getAllMembers: async (): Promise<Array<{ id: string; name: string }>> => {
    const r = await api.get('/api/bestellungen/members');
    return r.data.data;
  },

  // ── Catalog ──
  getKatalogItems: async (filters?: { search?: string; kategorie?: string }): Promise<AusruestungArtikel[]> => {
    const params = new URLSearchParams();
    if (filters?.search) params.set('search', filters.search);
    if (filters?.kategorie) params.set('kategorie', filters.kategorie);
    const r = await api.get(`/api/bestellungen/katalog/items?${params.toString()}`);
    return r.data.data;
  },
  getKatalogItem: async (id: number): Promise<AusruestungArtikel> => {
    const r = await api.get(`/api/bestellungen/katalog/items/${id}`);
    return r.data.data;
  },
  getKatalogKategorien: async (): Promise<string[]> => {
    const r = await api.get('/api/bestellungen/katalog/kategorien');
    return r.data.data;
  },
};
