import axios from 'axios';
import { GlobalFunctions } from '@/GlobalFunctions';

export interface AsanaWorkspaceResponse {
  gid: string;
  resource_type: string;
  name: string;
}

export interface AsanaWorkspacesResponse {
  data: AsanaWorkspaceResponse[];
}

export interface AsanaWorkspace {
  id: string;
  name: string;
}

export interface AsanaUserResponse {
  gid: string;
  name: string;
  resource_type: string;
}

export interface AsanaUsersResponse {
  data: AsanaUserResponse[];
}

export interface AsanaUser {
  id: string;
  name: string;
}

export interface AsanaIntegrationResponse {
  success: boolean;
  integracao_id?: string;
  id?: string;
  api_key?: string;
  workspace_gid?: string;
  workspace_nome?: string;
  usuario_asana_gid?: string;
  usuario_asana_nome?: string;
}

export interface AsanaIntegrationRequest {
  user_id?: string;
  api_key: string;
  workspace_gid: string;
  workspace_nome: string;
  usuario_asana_gid: string;
  usuario_asana_nome: string;
}

type AxiosLikeError = { response?: { data?: { message?: string }; status?: number } };

class AsanaService {
  private readonly ASANA_BASE_URL = 'https://app.asana.com/api/1.0';

  private asanaHeaders(token: string): Record<string, string> {
    return {
      accept: 'application/json',
      authorization: `Bearer ${token.trim()}`,
    };
  }

  private async n8nHeaders(): Promise<Record<string, string>> {
    const token = await GlobalFunctions.getToken();
    const apiKey = import.meta.env.VITE_API_KEY || '';
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      accept: 'application/json',
    };
    if (apiKey) headers['apikey'] = apiKey;
    if (token) headers['Authorization'] = `Bearer ${token}`;
    return headers;
  }

  private handleAsanaError(error: unknown, fallback: string): never {
    const e = error as AxiosLikeError;
    if (e?.response?.status === 401) {
      throw { success: false, message: 'Token inválido ou expirado. Verifique sua chave de API.' };
    }
    if (e?.response?.data) {
      throw { success: false, message: e.response.data.message || fallback };
    }
    throw { success: false, message: error instanceof Error ? error.message : fallback };
  }

  async getWorkspaces(token: string): Promise<AsanaWorkspace[]> {
    if (!token?.trim()) {
      throw { success: false, message: 'Token do Asana é obrigatório' };
    }

    try {
      const response = await axios.get<AsanaWorkspacesResponse>(
        `${this.ASANA_BASE_URL}/workspaces`,
        { headers: this.asanaHeaders(token) }
      );
      return response.data.data.map((w) => ({ id: w.gid, name: w.name }));
    } catch (error: unknown) {
      console.error('Erro ao buscar workspaces do Asana:', error);
      this.handleAsanaError(error, 'Erro ao buscar workspaces do Asana');
    }
  }

  async getUsers(token: string, workspaceId: string): Promise<AsanaUser[]> {
    if (!token?.trim()) {
      throw { success: false, message: 'Token do Asana é obrigatório' };
    }
    if (!workspaceId?.trim()) {
      throw { success: false, message: 'ID do workspace é obrigatório' };
    }

    try {
      const response = await axios.get<AsanaUsersResponse>(
        `${this.ASANA_BASE_URL}/users?workspace=${workspaceId}`,
        { headers: this.asanaHeaders(token) }
      );
      return response.data.data.map((u) => ({ id: u.gid, name: u.name }));
    } catch (error: unknown) {
      console.error('Erro ao buscar usuários do Asana:', error);
      this.handleAsanaError(error, 'Erro ao buscar usuários do Asana');
    }
  }

  async getIntegration(userId: string): Promise<AsanaIntegrationResponse | null> {
    if (!userId?.trim()) {
      throw { success: false, message: 'ID do usuário é obrigatório' };
    }

    try {
      const headers = await this.n8nHeaders();
      const response = await axios.get<AsanaIntegrationResponse>(
        `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/c898beff-84cb-44df-a69c-6eff27ccd7aa/codex/agente-pessoal/integracoes/asana/${userId}`,
        { headers }
      );
      return response.data.success ? response.data : null;
    } catch (error: unknown) {
      const e = error as AxiosLikeError;
      if (e?.response?.status === 404) return null;
      return null;
    }
  }

  async createIntegration(request: AsanaIntegrationRequest): Promise<AsanaIntegrationResponse> {
    if (!request.user_id || !request.api_key || !request.workspace_gid || !request.usuario_asana_gid) {
      throw { success: false, message: 'Dados incompletos para criar integração' };
    }

    try {
      const headers = await this.n8nHeaders();
      const response = await axios.post<AsanaIntegrationResponse>(
        'https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/agente-pessoal/integracoes/asana',
        request,
        { headers }
      );
      return response.data;
    } catch (error: unknown) {
      console.error('Erro ao criar integração do Asana:', error);
      this.handleAsanaError(error, 'Erro ao criar integração do Asana');
    }
  }

  async updateIntegration(
    integracaoId: string,
    request: Omit<AsanaIntegrationRequest, 'user_id'>
  ): Promise<AsanaIntegrationResponse> {
    if (!integracaoId || !request.api_key || !request.workspace_gid || !request.usuario_asana_gid) {
      throw { success: false, message: 'Dados incompletos para atualizar integração' };
    }

    try {
      const headers = await this.n8nHeaders();
      const response = await axios.post<AsanaIntegrationResponse>(
        `https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/c898beff-84cb-44df-a69c-6eff27ccd7aa/codex/agente-pessoal/integracoes/asana/${integracaoId}`,
        request,
        { headers }
      );
      return response.data;
    } catch (error: unknown) {
      console.error('Erro ao atualizar integração do Asana:', error);
      this.handleAsanaError(error, 'Erro ao atualizar integração do Asana');
    }
  }
}

export const asanaService = new AsanaService();
