// app/files/[...slug]/route.ts

import fs from 'fs';
import { NextRequest, NextResponse } from 'next/server';
import path from 'path';

const isProd = process.env.NODE_ENV === "production";
const DATA_DIR = isProd ? "/app/data" : path.join(process.cwd(), "app/data");
const FILES_DIR = path.join(DATA_DIR, "files");

export async function GET(
    request: NextRequest,
    { params }: { params: Promise<{ slug: string[] }> }
) {
    try {
        const resolvedParams = await params;
        const filename = decodeURIComponent(resolvedParams.slug[resolvedParams.slug.length - 1]);
        const filePath = path.join(FILES_DIR, filename);

        if (!fs.existsSync(filePath)) {
            console.error(`404 - Filen finns inte på disk: ${filePath}`);
            return new NextResponse('Filen hittades inte', { status: 404 });
        }

        const fileBuffer = fs.readFileSync(filePath);

        let contentType = 'application/pdf';
        if (filename.toLowerCase().endsWith('.png')) contentType = 'image/png';
        else if (filename.toLowerCase().endsWith('.jpg') || filename.toLowerCase().endsWith('.jpeg')) contentType = 'image/jpeg';
        else if (filename.toLowerCase().endsWith('.doc') || filename.toLowerCase().endsWith('.docx')) contentType = 'application/msword';

        return new NextResponse(fileBuffer, {
            headers: {
                'Content-Type': contentType,
                'Content-Disposition': `inline; filename="${filename}"`
            },
        });
    } catch (error) {
        console.error("Fel vid fildelning:", error);
        return new NextResponse('Ett internt serverfel uppstod', { status: 500 });
    }
}