/** Production Orders resource – Production BC. */

import type { AxiosInstance } from 'axios';
import type { ProductionOrderDTO, CreateProductionOrderRequest, RescheduleProductionOrderRequest } from '@effigenix/types';

export type Priority = 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT';

export const PRIORITY_LABELS: Record<Priority, string> = {
  LOW: 'Niedrig',
  NORMAL: 'Normal',
  HIGH: 'Hoch',
  URGENT: 'Dringend',
};

export type ProductionOrderStatus = 'PLANNED' | 'RELEASED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED';

export const PRODUCTION_ORDER_STATUS_LABELS: Record<ProductionOrderStatus, string> = {
  PLANNED: 'Geplant',
  RELEASED: 'Freigegeben',
  IN_PROGRESS: 'In Produktion',
  COMPLETED: 'Abgeschlossen',
  CANCELLED: 'Storniert',
};

export interface ProductionOrderFilter {
  status?: ProductionOrderStatus;
  dateFrom?: string;
  dateTo?: string;
}

export type { ProductionOrderDTO, CreateProductionOrderRequest, RescheduleProductionOrderRequest };

const BASE = '/api/production/production-orders';

export function createProductionOrdersResource(client: AxiosInstance) {
  return {
    async list(filter?: ProductionOrderFilter): Promise<ProductionOrderDTO[]> {
      const params: Record<string, string> = {};
      if (filter?.status) params.status = filter.status;
      if (filter?.dateFrom) params.dateFrom = filter.dateFrom;
      if (filter?.dateTo) params.dateTo = filter.dateTo;
      const res = await client.get<ProductionOrderDTO[]>(BASE, { params });
      return res.data;
    },

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

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

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

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

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

export type ProductionOrdersResource = ReturnType<typeof createProductionOrdersResource>;
