import axios from "axios";
import { Client, FolderStatus, Task, User, Document, ActivityLog } from '@/types/types';

// Utiliser une URL relative pour rester sur la même origine (évite CORS)
const API_URL = '/api';

console.log('API URL:', API_URL);

const apiInstance = axios.create({
    baseURL: API_URL,
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    // Même origine: les cookies NextAuth seront envoyés automatiquement
    withCredentials: true,
    timeout: 10000
});

// Ajouter un intercepteur pour inclure les tokens dans les requêtes
apiInstance.interceptors.request.use(
    async (config) => {
        // Ne pas ajouter le token pour les routes d'authentification
        if (config.url?.includes('/auth/')) {
            return config;
        }
        
        // NextAuth gère automatiquement l'authentification via les cookies
        // Pas besoin d'ajouter manuellement un header Authorization
        console.log('🔐 Request interceptor - URL:', config.url, 'Method:', config.method);
        return config;
    },
    (error) => {
        console.error('❌ Request interceptor error:', error);
        return Promise.reject(error);
    }
);

// Add request interceptor for debugging
apiInstance.interceptors.request.use(
    (config) => {
        console.log('Request:', {
            method: config.method?.toUpperCase(),
            url: config.url,
            data: config.data,
            headers: config.headers
        });
        return config;
    },
    (error) => {
        console.error('Request Error:', error);
        return Promise.reject(error);
    }
);

// Add response interceptor for better error handling
apiInstance.interceptors.response.use(
    (response) => {
        console.log('Response:', {
            status: response.status,
            data: response.data,
            headers: response.headers
        });
        return response;
    },
    async (error) => {
        if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            console.error('❌ Response Error:', {
                status: error.response.status,
                data: error.response.data,
                headers: error.response.headers,
                url: error.config?.url,
                method: error.config?.method
            });
            
            // If it's a 401 error, let's check if we're authenticated
            if (error.response.status === 401) {
                console.log('🔍 401 Error detected - checking authentication status...');
                try {
                    const sessionResponse = await fetch('/api/auth/session');
                    const session = await sessionResponse.json();
                    console.log('🔍 Current session:', session);
                } catch (sessionError) {
                    console.error('🔍 Error checking session:', sessionError);
                }
            }
        } else if (error.request) {
            // The request was made but no response was received
            console.error('Request Error: No response received', {
                request: error.request,
                message: error.message,
                code: error.code
            });
        } else {
            // Something happened in setting up the request that triggered an Error
            console.error('Error:', {
                message: error.message,
                stack: error.stack
            });
        }
        return Promise.reject(error);
    }
);

export async function loginUser(credentials: any) {
    return await apiInstance.post("/authentication/login", credentials)
        .then(res => res)
        .catch(err => err);
}

export const getClients = async (): Promise<Client[]> => {
    try {
        console.log('Fetching clients from:', `${API_URL}/clients`);
        const response = await apiInstance.get("/clients");
        console.log('Clients response:', response);
        return response.data;
    } catch (error: any) {
        if (error.response && (error.response.status === 401 || error.response.status === 403)) {
            console.error('Non autorisé : la session est absente ou expirée.');
        } else {
            console.error('Erreur lors de la récupération des clients:', error);
        }
        return [];
    }
};

export const getClient = async (id: string): Promise<Client> => {
    try {
        const response = await apiInstance.get(`/clients/${id}`);
        return response.data;
    } catch (error) {
        console.error('Error fetching client:', error);
        throw error;
    }
};

export const createClient = async (clientData: Partial<Client>): Promise<Client> => {
    try {
        const response = await apiInstance.post("/clients", clientData);
        return response.data;
    } catch (error) {
        console.error('Error creating client:', error);
        throw error;
    }
};

export const updateClient = async (id: string, clientData: Partial<Client>): Promise<Client> => {
  try {
    const response = await apiInstance.put(`/clients/${id}`, clientData);
    return response.data;
  } catch (error) {
    console.error('Error updating client:', error);
    throw error;
  }
};

export const deleteClient = async (id: string): Promise<void> => {
  console.log('🔍 deleteClient called with id:', id);
  try {
    const response = await apiInstance.delete(`/clients/${id}`);
    console.log('✅ deleteClient response:', response);
  } catch (error) {
    console.error('❌ Error deleting client:', error);
    throw error;
  }
};

// ✅ Fonction corrigée selon le modèle Prisma : on envoie firstName, lastName, status, clientId
export async function createFolder(clientId: number, status: string, firstName: string, lastName: string) {
    // Vérification de la présence des champs requis
    if (!firstName || !lastName) {
        console.error("Erreur : Les champs 'firstName' et 'lastName' sont requis.");
        return { error: "Les champs 'firstName' et 'lastName' sont requis." };
    }
    console.log("Payload envoyé :", { clientId, status, firstName, lastName });

    return apiInstance.post('/folders', {
        clientId,
        status,
        firstName,
        lastName
    }).then((response) => response)
      .catch((err) => {
          console.error("Erreur lors de la création du folder :", err.response?.data || err);
          return err;
      });
}

export async function getFolders() {
    return apiInstance.get('/folders')
        .then((response) => response)
        .catch((err) => err);
}

export async function getFolderById(id) {
    return apiInstance.get(`/folders/${id}`)
        .then((response) => response)
        .catch((err) => err);
}

export async function getRecentsFolders() {
    return apiInstance.get('/folders/recents')
        .then((response) => response)
        .catch((err) => err);
}
export const deleteFolder = async (id: number) => {
    return await apiInstance.delete(`/folders/${id}`);
};
export const updateFolder = async (id: number, data: any) => {
    return await apiInstance.put(`/folders/${id}`, data);
  };

  export const getFolder = async (id: number) => {
    return await apiInstance.get(`/folders/${id}`);
  };
  
  export const getAllPartners = async () => {
    const response = await apiInstance.get('/partners');
    return response.data;
  };
  

// Task API functions
export const getTasks = async (responsibleId?: number): Promise<Task[]> => {
    try {
        const params = new URLSearchParams();
        if (responsibleId) {
            params.append('responsibleId', responsibleId.toString());
        }
        const response = await apiInstance.get("/tasks", { params });
        return response.data;
    } catch (error) {
        console.error('Error fetching tasks:', error);
            return [];
    }
};

export const createTask = async (taskData: Partial<Task>): Promise<Task> => {
    try {
        const response = await apiInstance.post("/tasks", taskData);
        return response.data;
    } catch (error) {
        console.error('Error creating task:', error);
        throw error;
    }
};

export const updateTask = async (id: number, taskData: Partial<Task>): Promise<Task> => {
    try {
        const response = await apiInstance.put(`/tasks/${id}`, taskData);
        return response.data;
    } catch (error) {
        console.error('Error updating task:', error);
        throw error;
    }
};

export const getTask = async (id: number): Promise<Task> => {
    try {
        const response = await apiInstance.get(`/tasks/${id}`);
        return response.data;
    } catch (error) {
        console.error('Error fetching task:', error);
        throw error;
    }
};

export const getTaskById = async (id: number): Promise<Task> => {
    try {
        const response = await apiInstance.get(`/tasks/${id}`);
        return response.data;
    } catch (error) {
        console.error('Error fetching task by ID:', error);
        throw error;
    }
};

export const deleteTask = async (id: number): Promise<void> => {
    try {
        await apiInstance.delete(`/tasks/${id}`);
    } catch (error) {
        console.error('Error deleting task:', error);
        throw error;
    }
};

// Document functions
export const getDocuments = async (paramsObj?: { clientId?: number; isPermanent?: string }): Promise<Document[]> => {
  try {
    const params = new URLSearchParams();
    if (paramsObj?.clientId) {
      params.append('clientId', paramsObj.clientId.toString());
    }
    if (paramsObj?.isPermanent && paramsObj.isPermanent !== 'all') {
      params.append('isPermanent', paramsObj.isPermanent === 'true' ? 'true' : 'false');
    }
    const response = await apiInstance.get("/documents", { params });
    return response.data;
  } catch (error) {
    console.error('Error fetching documents:', error);
    return [];
  }
};

export const getDocument = async (id: number): Promise<Document> => {
  try {
    const response = await apiInstance.get(`/documents/${id}`);
    return response.data;
  } catch (error) {
    console.error('Error fetching document:', error);
    throw error;
  }
};

export const createDocument = async (documentData: Partial<Document>): Promise<Document> => {
  try {
    const response = await apiInstance.post("/documents", documentData);
    return response.data;
  } catch (error) {
    console.error('Error creating document:', error);
    throw error;
  }
};

export const updateDocument = async (id: number, documentData: Partial<Document>): Promise<Document> => {
  try {
    const response = await apiInstance.put(`/documents/${id}`, documentData);
    return response.data;
  } catch (error) {
    console.error('Error updating document:', error);
    throw error;
  }
};

export const deleteDocument = async (id: number): Promise<void> => {
  try {
    await apiInstance.delete(`/documents/${id}`);
  } catch (error) {
    console.error('Error deleting document:', error);
    throw error;
  }
};

export const uploadFile = async (formData: FormData): Promise<{ path: string }> => {
  try {
    const response = await apiInstance.post("/upload", formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    return response.data;
  } catch (error) {
    console.error('Error uploading file:', error);
    throw error;
  }
};

export const getUsers = async (): Promise<User[]> => {
  try {
    const response = await apiInstance.get("/users");
    return response.data;
  } catch (error) {
    console.error('Error fetching users:', error);
    return [];
  }
};

export const addCollaboratorToTask = async (taskId: number, email: string): Promise<any> => {
  try {
    const response = await apiInstance.post(`/tasks/${taskId}/collaborators`, { email });
    return response.data;
  } catch (error) {
    console.error('Error adding collaborator:', error);
    throw error;
  }
};

export const removeCollaboratorFromTask = async (taskId: number, userId: number): Promise<any> => {
  try {
    const response = await apiInstance.delete(`/tasks/${taskId}/collaborators`, { params: { userId } });
    return response.data;
  } catch (error) {
    console.error('Error removing collaborator:', error);
    throw error;
  }
};

export const getActivityLogs = async (clientId: number): Promise<ActivityLog[]> => {
  try {
    const response = await apiInstance.get(`/activity-logs`, { params: { clientId } });
    return response.data;
  } catch (error) {
    console.error('Error fetching activity logs:', error);
    return [];
  }
};

export const addActivityComment = async (clientId: number, userId: number, description: string): Promise<ActivityLog> => {
  try {
    const response = await apiInstance.post('/activity-logs', { clientId, userId, description });
    return response.data;
  } catch (error) {
    console.error('Error adding activity comment:', error);
    throw error;
  }
};

export const getFactures = async (): Promise<any[]> => {
  try {
    const response = await apiInstance.get("/factures");
    return response.data;
  } catch (error) {
    console.error('Error fetching factures:', error);
    return [];
  }
};
  
  