import { getToken } from "./auth";

const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8521";

export interface ApiUser {
    id: string;
    name: string;
    email: string;
    identifier: string;
    phone?: string;
    role: string;
    status: string;
    created_at: string;
}

export interface ApiCompany {
    id: string;
    name: string;
    slug: string;
    email?: string;
    phone?: string;
    website?: string;
    address?: string;
    active: boolean;
    verified: boolean;
    created_at: string;
}

async function apiRequest<T>(
    endpoint: string,
    options: RequestInit = {}
): Promise<T> {
    const token = getToken();

    // Sanitize API_URL: remove trailing slash
    let baseUrl = API_URL.replace(/\/+$/, "");

    // Sanitize endpoint: ensure leading slash
    let cleanEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`;

    // Detect and fix double prefixing of /api/v1
    // Case 1: BaseURL ends with /api/v1 AND endpoint starts with /api/v1
    if (baseUrl.endsWith("/api/v1") && cleanEndpoint.startsWith("/api/v1")) {
        cleanEndpoint = cleanEndpoint.replace("/api/v1", "");
    }

    // Case 2: Double /api/v1 inside endpoint itself (if passed incorrectly)
    if (cleanEndpoint.includes("/api/v1/api/v1")) {
        cleanEndpoint = cleanEndpoint.replace("/api/v1/api/v1", "/api/v1");
    }

    const url = `${baseUrl}${cleanEndpoint}`;
    console.log(`[API Request] ${url}`); // Debug log

    const res = await fetch(url, {
        ...options,
        headers: {
            "Content-Type": "application/json",
            ...(token && { Authorization: `Bearer ${token}` }),
            ...options.headers,
        },
    });

    if (!res.ok) {
        const error = await res.text();
        throw new Error(error || `API Error: ${res.status}`);
    }

    return res.json();
}

// Users API
export const usersApi = {
    list: () => apiRequest<ApiUser[]>("/api/v1/users"),

    create: (data: { name: string; email: string; password: string; role: string }) =>
        apiRequest<ApiUser>("/api/v1/users", {
            method: "POST",
            body: JSON.stringify(data),
        }),

    delete: (id: string) =>
        apiRequest<void>(`/api/v1/users/${id}`, {
            method: "DELETE",
        }),
};

// Companies API
export const companiesApi = {
    list: () => apiRequest<ApiCompany[]>("/api/v1/companies"),

    create: (data: { name: string; slug: string; email?: string }) =>
        apiRequest<ApiCompany>("/api/v1/companies", {
            method: "POST",
            body: JSON.stringify(data),
        }),
};

// Jobs API (public)
export const jobsApi = {
    list: () => apiRequest<unknown[]>("/jobs"),
};
