/** Inventory Counts resource – Inventory BC. */

import type { AxiosInstance } from 'axios';
import type {
  InventoryCountDTO,
  CreateInventoryCountRequest,
  RecordCountItemRequest,
  CancelInventoryCountRequest,
  InventoryCountStatus,
} from '@effigenix/types';

export type { InventoryCountDTO, CreateInventoryCountRequest, RecordCountItemRequest, CancelInventoryCountRequest, InventoryCountStatus };

export const INVENTORY_COUNT_STATUS_LABELS: Record<InventoryCountStatus, string> = {
  OPEN: 'Offen',
  COUNTING: 'In Zählung',
  COMPLETED: 'Abgeschlossen',
  CANCELLED: 'Abgebrochen',
};

export interface InventoryCountFilter {
  storageLocationId?: string;
  status?: string;
}

const BASE = '/api/inventory/inventory-counts';

export function createInventoryCountsResource(client: AxiosInstance) {
  return {
    async list(filter?: InventoryCountFilter): Promise<InventoryCountDTO[]> {
      const params: Record<string, string> = {};
      if (filter?.storageLocationId) params.storageLocationId = filter.storageLocationId;
      if (filter?.status) params.status = filter.status;
      const res = await client.get<InventoryCountDTO[]>(BASE, { params });
      return res.data;
    },

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

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

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

    async recordItem(countId: string, itemId: string, request: RecordCountItemRequest): Promise<InventoryCountDTO> {
      const res = await client.patch<InventoryCountDTO>(`${BASE}/${countId}/items/${itemId}`, request);
      return res.data;
    },

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

    async cancel(id: string, request: CancelInventoryCountRequest): Promise<InventoryCountDTO> {
      const res = await client.post<InventoryCountDTO>(`${BASE}/${id}/cancel`, request);
      return res.data;
    },
  };
}

export type InventoryCountsResource = ReturnType<typeof createInventoryCountsResource>;
