import { apiService } from "./api";

export interface PromptItem {
  id: string;
  titulo: string;
  descricao: string;
  conteudo: string;
  area_id: string;
  area_nome: string;
  created_at: string;
  updated_at: string;
}

export interface ListarPromptsParams {
  titulo?: string;
  area_id?: string;
  page: number;
  per_page: number;
}

export interface ListarPromptsResponseBody {
  success: true;
  total_registros: number;
  total_paginas: number;
  per_page: number;
  pagina_atual: number;
  data: PromptItem[];
}

export interface ListarPromptsPorAreaResponse {
  success: boolean;
  quantidade?: number;
  data: PromptItem[];
}

export interface CriarPromptBody {
  titulo: string;
  descricao: string;
  area_id: string;
  conteudo: string;
}

export interface CriarPromptSuccessResponse {
  success: true;
  id: string;
  titulo: string;
  descricao: string;
  conteudo: string;
}

export interface CriarPromptErrorResponse {
  success: false;
  missing_fields?: string[];
}

export interface EditarPromptBody {
  titulo: string;
  descricao: string;
  area_id: string;
  conteudo: string;
}

export interface EditarPromptSuccessResponse {
  success: true;
  id: string;
  titulo: string;
  descricao: string;
  area_id: string;
  conteudo: string;
}

export interface EditarPromptErrorResponse {
  success: false;
  missing_fields?: string[];
}

export interface DeletarPromptSuccessResponse {
  success: true;
  message: string;
}

export interface DeletarPromptErrorResponse {
  success: false;
  message?: string;
}

class PromptsService {
  async listar(params: ListarPromptsParams): Promise<ListarPromptsResponseBody> {
    const { page, per_page, titulo, area_id } = params;

    const response = await apiService.get<ListarPromptsResponseBody[]>(
      "https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/parecer/prompts",
      {
        params: {
          ...(titulo != null && titulo.trim() !== "" ? { titulo: titulo.trim() } : {}),
          ...(area_id != null && area_id.trim() !== "" ? { area_id: area_id.trim() } : {}),
          page,
          per_page,
        },
      }
    );

    const first = Array.isArray(response.data) ? response.data[0] : response.data;

    if (!first || first.success !== true) {
      throw new Error("Resposta inválida ao listar prompts");
    }

    return first;
  }

  async listarPorArea(areaId: string): Promise<ListarPromptsPorAreaResponse> {
    if (!areaId?.trim()) {
      return { success: true, quantidade: 0, data: [] };
    }

    const areaIdEnc = encodeURIComponent(areaId.trim());

    const response = await apiService.get<ListarPromptsPorAreaResponse | ListarPromptsPorAreaResponse[]>(
      `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/parecer/prompts/listar-todos-area?area_id=${areaIdEnc}`
    );

    const first = Array.isArray(response.data) ? response.data[0] : response.data;

    if (!first || first.success !== true) {
      throw new Error("Resposta inválida ao listar prompts da área");
    }

    const list = first.data ?? [];
    return { success: true, quantidade: first.quantidade ?? list.length, data: list };
  }

  async criar(body: CriarPromptBody): Promise<CriarPromptSuccessResponse> {
    if (!body.titulo?.trim() || !body.area_id?.trim() || !body.conteudo?.trim()) {
      throw new Error("Título, área e conteúdo são obrigatórios");
    }

    const response = await apiService.post<CriarPromptSuccessResponse | CriarPromptErrorResponse>(
      "https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/parecer/prompt/criar",
      {
        titulo: body.titulo.trim(),
        descricao: (body.descricao ?? "").trim(),
        area_id: body.area_id.trim(),
        conteudo: body.conteudo.trim(),
      }
    );

    if (response.data.success === false) {
      const err = response.data as CriarPromptErrorResponse;
      const msg = err.missing_fields?.length
        ? `Preencha: ${err.missing_fields.join(", ")}`
        : "Erro ao criar prompt.";
      throw new Error(msg);
    }

    return response.data as CriarPromptSuccessResponse;
  }

  async editar(id: string, body: EditarPromptBody): Promise<EditarPromptSuccessResponse> {
    if (!id?.trim()) {
      throw new Error("ID do prompt é obrigatório");
    }

    const idEnc = encodeURIComponent(id.trim());
    /** Mesmo prefixo de webhook n8n usado em edição de área (`areas.editar`). */
    const url = `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/parecer/prompt/${idEnc}`;

    const response = await apiService.put<
      EditarPromptSuccessResponse | EditarPromptErrorResponse | (EditarPromptSuccessResponse | EditarPromptErrorResponse)[]
    >(url, {
      titulo: (body.titulo ?? "").trim(),
      descricao: (body.descricao ?? "").trim(),
      area_id: body.area_id.trim(),
      conteudo: (body.conteudo ?? "").trim(),
    });

    const raw = response.data;
    const data = Array.isArray(raw) ? raw[0] : raw;

    if (!data || typeof data !== "object" || !("success" in data)) {
      throw new Error("Resposta inválida ao editar prompt");
    }

    if (data.success === false) {
      const err = data as EditarPromptErrorResponse;
      const msg = err.missing_fields?.length
        ? `Preencha: ${err.missing_fields.join(", ")}`
        : "Erro ao editar prompt.";
      throw new Error(msg);
    }

    return data as EditarPromptSuccessResponse;
  }

  async deletar(id: string): Promise<DeletarPromptSuccessResponse> {
    if (!id?.trim()) {
      throw new Error("ID do prompt é obrigatório");
    }

    const idEnc = encodeURIComponent(id.trim());
    const url = `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/4e6c2374-9c22-4c81-b558-45f0cfefa5c3/codex/parecer/prompt/deletar/${idEnc}`;

    const response = await apiService.delete<
      DeletarPromptSuccessResponse | DeletarPromptErrorResponse | (DeletarPromptSuccessResponse | DeletarPromptErrorResponse)[]
    >(url);

    const raw = response.data;
    const data = Array.isArray(raw) ? raw[0] : raw;

    if (!data || typeof data !== "object" || !("success" in data)) {
      throw new Error("Resposta inválida ao excluir prompt");
    }

    if (data.success === false) {
      const err = data as DeletarPromptErrorResponse;
      throw new Error(err.message ?? "Erro ao excluir prompt.");
    }

    return data as DeletarPromptSuccessResponse;
  }
}

export const promptsService = new PromptsService();
