import axios from "axios";

import { buildCommanderHeaders, resolveCommanderBaseUrl } from "./commanderHttp";

export type UsuarioPapel = "admin" | "parceiro";
export type UsuarioStatusFiltro = "all" | "true" | "false";

export type UsuarioItem = {
  id: string;
  parceiroId: string | null;
  nome: string | null;
  email: string | null;
  papel: UsuarioPapel;
  estaAtivo: boolean;
  criadoEm: string;
  atualizadoEm: string;
};

type MetaResponse = {
  total: number;
  paginaAtual: number;
  totalPaginas: number;
};

type ListarUsuariosResponse = {
  data: UsuarioItem[];
  meta: MetaResponse;
};

type ApiErrorShape = {
  error?: {
    message?: string;
  };
};

export type ListarUsuariosParams = {
  busca?: string;
  papel?: UsuarioPapel;
  estaAtivo?: UsuarioStatusFiltro;
  page: number;
  perPage: number;
};

export type SalvarUsuarioPayload = {
  nome?: string | null;
  email?: string | null;
  papel: UsuarioPapel;
  parceiroId?: string | null;
  estaAtivo?: boolean;
};

type SalvarUsuarioResponse = {
  data: UsuarioItem;
};

class FechamentoUsuariosService {
  private handleAxiosError(error: unknown, fallback: string): never {
    if (axios.isAxiosError(error)) {
      if (!error.response) {
        throw new Error(
          "Não foi possível conectar na API do Commander. Verifique VITE_API_BASE_URL_COMMANDER e se o backend está acessível.",
        );
      }
      const message = ((error.response.data as ApiErrorShape | undefined)?.error?.message ??
        error.message ??
        fallback) as string;
      throw new Error(message);
    }
    throw new Error(fallback);
  }

  async listarUsuarios(params: ListarUsuariosParams): Promise<ListarUsuariosResponse> {
    try {
      const headers = await buildCommanderHeaders();
      const baseUrl = resolveCommanderBaseUrl();
      const response = await axios.get<ListarUsuariosResponse>(`${baseUrl}/usuarios`, {
        headers,
        params: {
          busca: params.busca || undefined,
          papel: params.papel || undefined,
          estaAtivo: params.estaAtivo ?? "all",
          page: params.page,
          perPage: params.perPage,
        },
      });
      return response.data;
    } catch (error) {
      this.handleAxiosError(error, "Erro ao listar usuários.");
    }
  }

  async criarUsuario(payload: SalvarUsuarioPayload): Promise<UsuarioItem> {
    try {
      const headers = await buildCommanderHeaders();
      const baseUrl = resolveCommanderBaseUrl();
      const response = await axios.post<SalvarUsuarioResponse>(`${baseUrl}/usuarios`, payload, { headers });
      return response.data.data;
    } catch (error) {
      this.handleAxiosError(error, "Erro ao criar usuário.");
    }
  }

  async editarUsuario(id: string, payload: Partial<SalvarUsuarioPayload>): Promise<UsuarioItem> {
    try {
      const headers = await buildCommanderHeaders();
      const baseUrl = resolveCommanderBaseUrl();
      const response = await axios.patch<SalvarUsuarioResponse>(`${baseUrl}/usuarios/${id}`, payload, {
        headers,
      });
      return response.data.data;
    } catch (error) {
      this.handleAxiosError(error, "Erro ao editar usuário.");
    }
  }

  async toggleAtivoUsuario(id: string): Promise<UsuarioItem> {
    try {
      const headers = await buildCommanderHeaders();
      const baseUrl = resolveCommanderBaseUrl();
      const response = await axios.patch<SalvarUsuarioResponse>(
        `${baseUrl}/usuarios/${id}/toggle-ativo`,
        {},
        { headers },
      );
      return response.data.data;
    } catch (error) {
      this.handleAxiosError(error, "Erro ao atualizar status do usuário.");
    }
  }
}

export const fechamentoUsuariosService = new FechamentoUsuariosService();
