const API_BASE = "http://localhost:36969/api";

export interface ScanResult {
    path: string;
    size: number;
    isDirectory: boolean;
}

export interface DiskUsage {
    totalGB: string;
    usedGB: string;
    freeGB: string;
}

export interface CategorySizes {
    documents: number;
    downloads: number;
    desktop: number;
    music: number;
    movies: number;
    system: number;
    trash: number;
    apps: number;
    photos: number;
    icloud: number;
}

export interface SystemInfo {
    model: string;
    chip: string;
    memory: string;
    os: string;
}

export interface CleaningEstimates {
    flash_est: number;
    deep_est: number;
}

// Uninstaller Types
export interface AppInfo {
    name: string;
    path: string;
    bundleID: string;
    size: number;
    icon?: string;
}

export interface AssociatedFile {
    path: string;
    type: 'cache' | 'config' | 'log' | 'data';
    size: number;
}

export interface AppDetails extends AppInfo {
    associated: AssociatedFile[];
    totalSize: number;
}

export const API = {
    getDiskUsage: async (): Promise<DiskUsage | null> => {
        try {
            const res = await fetch(`${API_BASE}/disk-usage`);
            if (!res.ok) throw new Error("Failed to fetch disk usage");
            return await res.json();
        } catch (e) {
            console.error(e);
            return null;
        }
    },

    scanCategory: async (category: string): Promise<ScanResult[]> => {
        const res = await fetch(`${API_BASE}/scan/category`, {
            method: "POST",
            body: JSON.stringify({ category })
        });
        return await res.json() || [];
    },

    openSettings: async () => {
        await fetch(`${API_BASE}/open-settings`, { method: "POST" });
    },

    getCategorySizes: async (): Promise<CategorySizes> => {
        try {
            const res = await fetch(`${API_BASE}/scan/sizes`);
            return await res.json();
        } catch {
            return { documents: 0, downloads: 0, desktop: 0, music: 0, movies: 0, system: 0, trash: 0, apps: 0, photos: 0, icloud: 0 };
        }
    },

    deepestScan: async (): Promise<ScanResult[]> => {
        const res = await fetch(`${API_BASE}/scan/deepest`, { method: "POST" });
        return await res.json() || [];
    },

    purgePath: async (path: string): Promise<boolean> => {
        try {
            const res = await fetch(`${API_BASE}/purge`, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ path }),
            });
            return res.ok;
        } catch (e) {
            console.error(e);
            return false;
        }
    },

    emptyTrash: async (): Promise<boolean> => {
        try {
            const res = await fetch(`${API_BASE}/empty-trash`, { method: "POST" });
            return res.ok;
        } catch (e) {
            console.error(e);
            return false;
        }
    },

    clearCache: async (): Promise<{ cleared: number }> => {
        try {
            const res = await fetch(`${API_BASE}/clear-cache`, { method: "POST" });
            return await res.json();
        } catch (e) {
            console.error(e);
            return { cleared: 0 };
        }
    },

    cleanDocker: async (): Promise<{ cleared: number; message: string }> => {
        try {
            const res = await fetch(`${API_BASE}/clean-docker`, { method: "POST" });
            return await res.json();
        } catch (e) {
            console.error(e);
            return { cleared: 0, message: "Docker cleanup failed" };
        }
    },

    getSystemInfo: async (): Promise<SystemInfo | null> => {
        try {
            const res = await fetch(`${API_BASE}/system-info`);
            return await res.json();
        } catch (e) {
            console.error(e);
            return null;
        }
    },

    getEstimates: async (): Promise<CleaningEstimates | null> => {
        try {
            const res = await fetch(`${API_BASE}/estimates`);
            return await res.json();
        } catch (e) {
            console.error(e);
            return null;
        }
    },

    // Uninstaller APIs
    getApps: async (): Promise<AppInfo[]> => {
        const res = await fetch(`${API_BASE}/apps`);
        return res.json();
    },

    getAppDetails: async (path: string): Promise<AppDetails> => {
        const res = await fetch(`${API_BASE}/apps/details`, {
            method: 'POST',
            body: JSON.stringify({ path }),
        });
        return res.json();
    },

    deleteAppFiles: async (files: string[]): Promise<void> => {
        const res = await fetch(`${API_BASE}/apps/action`, {
            method: 'POST',
            body: JSON.stringify({ files }),
        });
        if (!res.ok) throw new Error("Failed to delete files");
    },

    getAppIcon: async (path: string): Promise<string> => {
        // Fallback or use Electron bridge directly
        if (window.electronAPI?.getAppIcon) {
            return window.electronAPI.getAppIcon(path);
        }
        return '';
    }
};
