import { Attachment, Bucket, dbSync } from "@/models";
import { open, openSync, readFileSync } from "fs";
import { NextRequest, NextResponse } from "next/server";
import path from "path";

export async function GET(req:NextRequest, { params }: {params:{slug: string[]}}){
    await dbSync;
    const filename: `${string}${'.'}${string}` = params.slug[params.slug.length-1] as `${string}${'.'}${string}`;
    const bucket = await Bucket.findOne({
        where: {
            id:params.slug[0],
        }, 
        include: [{
            association: Bucket.associations.attachments, 
            where: {
                filename: params.slug[params.slug.length-1]
            }
        }]
    },)
    console.log(params.slug);
    if(!bucket || !bucket.attachments || !bucket.attachments[0] || bucket.attachments[0].filename != params.slug[params.slug.length-1]){
        const headers = new Headers();
        headers.set("Content-Type", "application/json"); 
        return new NextResponse(JSON.stringify({
            error:"Access Denied"
        }),{headers:headers}); 
    } 
    const fp = path.resolve('.',`bucket`,...params.slug);
    return new Response(readFileSync(fp));
}