/** Batches resource – Production BC. */

import type { AxiosInstance } from 'axios';
import type {
  BatchDTO,
  BatchSummaryDTO,
  ConsumptionDTO,
  PlanBatchRequest,
  CompleteBatchRequest,
  RecordConsumptionRequest,
  CancelBatchRequest,
} from '@effigenix/types';

export type BatchStatus = 'PLANNED' | 'IN_PRODUCTION' | 'COMPLETED' | 'CANCELLED';

export const BATCH_STATUS_LABELS: Record<BatchStatus, string> = {
  PLANNED: 'Geplant',
  IN_PRODUCTION: 'In Produktion',
  COMPLETED: 'Abgeschlossen',
  CANCELLED: 'Storniert',
};

export type {
  BatchDTO,
  BatchSummaryDTO,
  ConsumptionDTO,
  PlanBatchRequest,
  CompleteBatchRequest,
  RecordConsumptionRequest,
  CancelBatchRequest,
};

const BASE = '/api/production/batches';

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

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

    async getByNumber(batchNumber: string): Promise<BatchDTO> {
      const res = await client.get<BatchDTO>(`${BASE}/by-number/${batchNumber}`);
      return res.data;
    },

    async plan(request: PlanBatchRequest): Promise<BatchDTO> {
      const res = await client.post<BatchDTO>(BASE, request);
      return res.data;
    },

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

    async recordConsumption(id: string, request: RecordConsumptionRequest): Promise<ConsumptionDTO> {
      const res = await client.post<ConsumptionDTO>(`${BASE}/${id}/consumptions`, request);
      return res.data;
    },

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

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

export type BatchesResource = ReturnType<typeof createBatchesResource>;
