"use client"; // ensures this runs only on client components

import axios from "axios";
import { redirect } from "next/navigation"; // use Next.js navigation

const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:3001/api";

// Create axios instance with default config
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    "Content-Type": "application/json",
  },
});

// Add auth token to requests
api.interceptors.request.use((config) => {
  if (typeof window !== "undefined") {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
  }
  return config;
});

// Handle auth errors globally
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401 && typeof window !== "undefined") {
      localStorage.removeItem("token");
      redirect("/login"); // ✅ Next.js way
    }
    return Promise.reject(error);
  }
);

// ------------------------
// Authentication API
// ------------------------
export const authApi = {
  login: async (email: string, password: string) => {
    const response = await api.post("/auth/login", { email, password });
    return response.data;
  },

  signup: async (name: string, email: string, password: string) => {
    const response = await api.post("/auth/signup", { name, email, password });
    return response.data;
  },

  verifyToken: async (token: string) => {
    const response = await api.get("/auth/verify", {
      headers: { Authorization: `Bearer ${token}` },
    });
    return response.data;
  },

  getUserStats: async () => {
    const response = await api.get("/auth/stats");
    return response.data;
  },
};

// ------------------------
// Processing API
// ------------------------
export const processingApi = {
  startBatch: async (files: File[], options: any, batchName?: string) => {
    const formData = new FormData();
    files.forEach((file) => formData.append("images", file));
    formData.append("options", JSON.stringify(options));
    if (batchName) formData.append("batchName", batchName);

    const response = await api.post("/processing/batch", formData, {
      headers: { "Content-Type": "multipart/form-data" },
      timeout: 300000, // 5 minutes for large batches
    });
    return response.data;
  },

  getBatchStatus: async (batchId: string) => {
    const response = await api.get(`/processing/batch/${batchId}`);
    return response.data;
  },

  getBatchHistory: async (limit = 20) => {
    const response = await api.get(`/processing/batches?limit=${limit}`);
    return response.data;
  },

  processSingleImage: async (file: File, options: any) => {
    const formData = new FormData();
    formData.append("image", file);
    formData.append("options", JSON.stringify(options));

    const response = await api.post("/processing/single", formData, {
      headers: { "Content-Type": "multipart/form-data" },
    });
    return response.data;
  },

  downloadBatch: async (batchId: string) => {
    const response = await api.get(`/processing/download/${batchId}`, {
      responseType: "blob",
    });

    if (typeof window !== "undefined") {
      // Create download link in browser
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", `optimized-images-${batchId}.zip`);
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    }
  },
};

// ------------------------
// Dashboard API
// ------------------------
export const dashboardApi = {
  getUserStats: async () => {
    const response = await api.get("/auth/stats");
    return response.data;
  },

  getBatchHistory: async (limit = 10) => {
    const response = await api.get(`/processing/batches?limit=${limit}`);
    return response.data;
  },
};

export default api;
export { api };
