import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { getWorkspacesRoot } from '@/lib/forge-data'

function validateFolderName(name: string): string | null {
    const trimmed = name.trim()

    if (!trimmed) return 'Folder name is required'
    if (trimmed === '.' || trimmed === '..') return 'Invalid folder name'
    if (trimmed.includes('/') || trimmed.includes('\\')) return 'Folder name cannot contain path separators'
    if (trimmed.includes('\0')) return 'Invalid folder name'

    return null
}

function isDirectChildOf(parentPath: string, childPath: string): boolean {
    const relative = path.relative(parentPath, childPath)
    return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative) && !relative.includes(path.sep)
}

export async function POST(req: NextRequest) {
    let body: Record<string, unknown>

    try {
        body = await req.json()
    } catch {
        return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
    }

    if (typeof body.name !== 'string') {
        return NextResponse.json({ error: 'name is required' }, { status: 400 })
    }

    const name = body.name.trim()
    const validationError = validateFolderName(name)
    if (validationError) {
        return NextResponse.json({ error: validationError }, { status: 400 })
    }

    const workspacesRoot = path.resolve(getWorkspacesRoot())
    const targetPath = path.resolve(workspacesRoot, name)

    if (!isDirectChildOf(workspacesRoot, targetPath)) {
        return NextResponse.json({ error: 'Folder must be created directly under workspaces root' }, { status: 400 })
    }

    if (fs.existsSync(targetPath)) {
        return NextResponse.json({ error: 'Folder already exists' }, { status: 409 })
    }

    try {
        fs.mkdirSync(targetPath)
    } catch {
        return NextResponse.json({ error: 'Failed to create folder' }, { status: 500 })
    }

    return NextResponse.json({
        name,
        path: targetPath,
    }, { status: 201 })
}
