import api from "./api";
import type {
  AutoCodeDto,
  AutoCodeUpdateDto,
  GenerateCodeResponse,
  ResetSequenceRequest,
  CheckUniqueResponse,
  PlaceholderInfo,
} from "../types/autoCode";

/**
 * Service per la gestione dei codici automatici
 */
export const autoCodeService = {
  /**
   * Ottiene tutte le configurazioni AutoCode
   */
  getAll: async (): Promise<AutoCodeDto[]> => {
    const response = await api.get("/autocodes");
    return response.data;
  },

  /**
   * Ottiene le configurazioni per un modulo specifico
   */
  getByModule: async (moduleCode: string): Promise<AutoCodeDto[]> => {
    const response = await api.get(`/autocodes/module/${moduleCode}`);
    return response.data;
  },

  /**
   * Ottiene una configurazione specifica per codice entita
   */
  getByEntityCode: async (entityCode: string): Promise<AutoCodeDto> => {
    const response = await api.get(`/autocodes/${entityCode}`);
    return response.data;
  },

  /**
   * Genera un nuovo codice per un'entita
   */
  generateCode: async (entityCode: string): Promise<GenerateCodeResponse> => {
    const response = await api.post(`/autocodes/${entityCode}/generate`);
    return response.data;
  },

  /**
   * Ottiene un'anteprima del prossimo codice senza incrementare la sequenza
   */
  previewCode: async (entityCode: string): Promise<GenerateCodeResponse> => {
    const response = await api.get(`/autocodes/${entityCode}/preview`);
    return response.data;
  },

  /**
   * Aggiorna una configurazione AutoCode
   */
  update: async (id: number, data: AutoCodeUpdateDto): Promise<AutoCodeDto> => {
    const response = await api.put(`/autocodes/${id}`, data);
    return response.data;
  },

  /**
   * Resetta la sequenza per un'entita
   */
  resetSequence: async (
    entityCode: string,
    request?: ResetSequenceRequest
  ): Promise<{ message: string }> => {
    const response = await api.post(`/autocodes/${entityCode}/reset-sequence`, request || {});
    return response.data;
  },

  /**
   * Verifica se un codice e unico per un'entita
   */
  checkUnique: async (
    entityCode: string,
    code: string,
    excludeId?: number
  ): Promise<CheckUniqueResponse> => {
    const response = await api.get(`/autocodes/${entityCode}/check-unique`, {
      params: { code, excludeId },
    });
    return response.data;
  },

  /**
   * Ottiene i placeholder disponibili per i pattern
   */
  getPlaceholders: async (): Promise<PlaceholderInfo[]> => {
    const response = await api.get("/autocodes/placeholders");
    return response.data;
  },
};

export default autoCodeService;
