import { getDbClient } from '@/app/lib/dbClient';
import { BillingLocation } from '@/app/lib/db-types';
import { notFound } from 'next/navigation';

export async function GET(request: Request, { params:{ id } }: { params: { id:string } }) {
    const locationID = id;

    const dbClient = await getDbClient();
    const location = await dbClient.collection<BillingLocation>("lokacije")
        .findOne({ _id: locationID }, {
            projection: {
                utilBillsProofOfPaymentAttachment: 1,
            }
        });

    if(!location?.utilBillsProofOfPaymentAttachment) {
        notFound();
    }

    // Convert fileContentsBase64 from Base64 string to binary
    const fileContentsBuffer = Buffer.from(location.utilBillsProofOfPaymentAttachment.fileContentsBase64, 'base64');

    // Convert fileContentsBuffer to format that can be sent to the client
    const fileContents = new Uint8Array(fileContentsBuffer);

    return new Response(fileContents, {
        status: 200,
        headers: {
            'Content-Type': 'application/pdf',
            'Content-Disposition': `attachment; filename="${location.utilBillsProofOfPaymentAttachment.fileName}"`,
            'Last-Modified': `${location.utilBillsProofOfPaymentAttachment.fileLastModified}`
        }
    });
}
