import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import os from 'os'

function getWorkspacesRoot(): string {
    if (process.env.FORGE_WORKSPACES_ROOT) {
        return process.env.FORGE_WORKSPACES_ROOT
    }
    return path.join(os.homedir(), 'workspaces')
}

interface QuickAccessEntry {
    label: string
    path: string
    icon: string
}

function buildQuickAccess(workspacesRoot: string): QuickAccessEntry[] {
    const entries: QuickAccessEntry[] = [
        { label: 'Workspaces', path: workspacesRoot, icon: 'home' },
        { label: 'Home', path: os.homedir(), icon: 'user' },
    ]

    const commonDirs: [string, string, string][] = [
        ['/opt', 'Opt', 'server'],
        ['/srv', 'Srv', 'server'],
        ['/data', 'Data', 'database'],
        ['/var/www', 'WWW', 'globe'],
    ]

    for (const [dir, label, icon] of commonDirs) {
        try {
            if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) {
                entries.push({ label, path: dir, icon })
            }
        } catch { /* skip */ }
    }

    return entries
}

export async function GET() {
    const workspacesRoot = getWorkspacesRoot()

    return NextResponse.json({
        home: os.homedir(),
        workspacesRoot,
        platform: process.platform,
        quickAccess: buildQuickAccess(workspacesRoot),
    })
}
