/**
 * StorageLocations resource – Inventory BC.
 * Endpoints: GET/POST /api/inventory/storage-locations,
 *   PUT /api/inventory/storage-locations/{id},
 *   PATCH /api/inventory/storage-locations/{id}/activate|deactivate
 */

import type { AxiosInstance } from 'axios';
import type {
  StorageLocationDTO,
  TemperatureRangeDTO,
  CreateStorageLocationRequest,
  UpdateStorageLocationRequest,
} from '@effigenix/types';

export type StorageType = 'COLD_ROOM' | 'FREEZER' | 'DRY_STORAGE' | 'DISPLAY_COUNTER' | 'PRODUCTION_AREA';

export const STORAGE_TYPE_LABELS: Record<StorageType, string> = {
  COLD_ROOM: 'Kühlraum',
  FREEZER: 'Tiefkühler',
  DRY_STORAGE: 'Trockenlager',
  DISPLAY_COUNTER: 'Vitrine',
  PRODUCTION_AREA: 'Produktionsbereich',
};

export type {
  StorageLocationDTO,
  TemperatureRangeDTO,
  CreateStorageLocationRequest,
  UpdateStorageLocationRequest,
};

export interface StorageLocationFilter {
  storageType?: string;
  active?: boolean;
}

// ── Resource factory ─────────────────────────────────────────────────────────

const BASE = '/api/inventory/storage-locations';

export function createStorageLocationsResource(client: AxiosInstance) {
  return {
    async list(filter?: StorageLocationFilter): Promise<StorageLocationDTO[]> {
      const params: Record<string, string> = {};
      if (filter?.storageType) params['storageType'] = filter.storageType;
      if (filter?.active !== undefined) params['active'] = String(filter.active);
      const res = await client.get<StorageLocationDTO[]>(BASE, { params });
      return res.data;
    },

    async getById(id: string): Promise<StorageLocationDTO> {
      const res = await client.get<StorageLocationDTO>(`${BASE}/${id}`);
      return res.data;
    },

    async create(request: CreateStorageLocationRequest): Promise<StorageLocationDTO> {
      const res = await client.post<StorageLocationDTO>(BASE, request);
      return res.data;
    },

    async update(id: string, request: UpdateStorageLocationRequest): Promise<StorageLocationDTO> {
      const res = await client.put<StorageLocationDTO>(`${BASE}/${id}`, request);
      return res.data;
    },

    async activate(id: string): Promise<StorageLocationDTO> {
      const res = await client.patch<StorageLocationDTO>(`${BASE}/${id}/activate`);
      return res.data;
    },

    async deactivate(id: string): Promise<StorageLocationDTO> {
      const res = await client.patch<StorageLocationDTO>(`${BASE}/${id}/deactivate`);
      return res.data;
    },
  };
}

export type StorageLocationsResource = ReturnType<typeof createStorageLocationsResource>;
