import axios from "axios";

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

export type AsanaWorkspaceUser = {
  id: string;
  name: string;
};

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

type AsanaWorkspaceUsersResponse = {
  data: Array<{
    gid: string;
    name?: string;
    email?: string;
  }>;
};

class FechamentoAsanaWorkspaceUsersService {
  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 listarUsuariosDoWorkspace(workspaceId: string): Promise<AsanaWorkspaceUser[]> {
    if (!workspaceId.trim()) {
      return [];
    }
    try {
      const headers = await buildCommanderHeaders();
      const baseUrl = resolveCommanderBaseUrl();
      const response = await axios.get<AsanaWorkspaceUsersResponse>(
        `${baseUrl}/asana/workspaces/${encodeURIComponent(workspaceId)}/users`,
        { headers },
      );

      return (response.data.data ?? []).map((item) => ({
        id: item.gid,
        name: item.name?.trim() || item.email?.trim() || item.gid,
      }));
    } catch (error) {
      this.handleAxiosError(error, "Erro ao listar usuários do workspace do Asana.");
    }
  }
}

export const fechamentoAsanaWorkspaceUsersService = new FechamentoAsanaWorkspaceUsersService();
