import { NextResponse } from 'next/server';
import fs from 'fs-extra';
import path from 'path';
import mime from 'mime';

export async function GET(request: Request) {
    const { searchParams } = new URL(request.url);
    const filePath = searchParams.get('path');

    if (!filePath) {
        return NextResponse.json({ error: 'Path is required' }, { status: 400 });
    }

    // Security check: Ensure we are only serving files from allowed locations?
    // For this local tool, we might be lenient, but ideally we should check if it's in the watch folder.
    // However, the watch folder location is dynamic.
    // Let's at least check if it exists.

    try {
        if (!await fs.pathExists(filePath)) {
            return NextResponse.json({ error: 'File not found' }, { status: 404 });
        }

        const stat = await fs.stat(filePath);
        if (!stat.isFile()) {
            return NextResponse.json({ error: 'Not a file' }, { status: 400 });
        }

        const fileBuffer = await fs.readFile(filePath);
        const contentType = mime.getType(filePath) || 'application/octet-stream';

        return new NextResponse(fileBuffer, {
            headers: {
                'Content-Type': contentType,
                'Content-Length': stat.size.toString(),
                'Cache-Control': 'public, max-age=3600'
            }
        });
    } catch (error) {
        console.error('Error serving file:', error);
        return NextResponse.json({ error: 'Failed to serve file' }, { status: 500 });
    }
}
