/** Stock Movements resource – Inventory BC. */

import type { AxiosInstance } from 'axios';
import type { StockMovementDTO, RecordStockMovementRequest } from '@effigenix/types';

export type MovementType =
  | 'GOODS_RECEIPT'
  | 'PRODUCTION_OUTPUT'
  | 'PRODUCTION_CONSUMPTION'
  | 'SALE'
  | 'RETURN'
  | 'WASTE'
  | 'ADJUSTMENT'
  | 'INTER_BRANCH_TRANSFER';

export const MOVEMENT_TYPE_LABELS: Record<MovementType, string> = {
  GOODS_RECEIPT: 'Wareneingang',
  PRODUCTION_OUTPUT: 'Produktionsausstoß',
  PRODUCTION_CONSUMPTION: 'Produktionsverbrauch',
  SALE: 'Verkauf',
  RETURN: 'Retoure',
  WASTE: 'Ausschuss',
  ADJUSTMENT: 'Korrektur',
  INTER_BRANCH_TRANSFER: 'Filialumlagerung',
};

export type MovementDirection = 'IN' | 'OUT';

export const MOVEMENT_DIRECTION_LABELS: Record<MovementDirection, string> = {
  IN: 'Eingang',
  OUT: 'Ausgang',
};

export type { StockMovementDTO, RecordStockMovementRequest };

export interface StockMovementFilter {
  stockId?: string;
  articleId?: string;
  movementType?: string;
  batchReference?: string;
  from?: string;
  to?: string;
}

const BASE = '/api/inventory/stock-movements';

export function createStockMovementsResource(client: AxiosInstance) {
  return {
    async list(filter?: StockMovementFilter): Promise<StockMovementDTO[]> {
      const params: Record<string, string> = {};
      if (filter?.stockId) params.stockId = filter.stockId;
      if (filter?.articleId) params.articleId = filter.articleId;
      if (filter?.movementType) params.movementType = filter.movementType;
      if (filter?.batchReference) params.batchReference = filter.batchReference;
      if (filter?.from) params.from = filter.from;
      if (filter?.to) params.to = filter.to;
      const res = await client.get<StockMovementDTO[]>(BASE, { params });
      return res.data;
    },

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

    async record(request: RecordStockMovementRequest): Promise<StockMovementDTO> {
      const res = await client.post<StockMovementDTO>(BASE, request);
      return res.data;
    },
  };
}

export type StockMovementsResource = ReturnType<typeof createStockMovementsResource>;
