import {readFile} from "node:fs/promises";
import path from "node:path";
import {eq} from "drizzle-orm";
import {getDb} from "../../../../db";
import {assignments,inspectionPhotos,inspections} from "../../../../db/schema";
import {getFleetUser} from "../../../../lib/fleet-auth";
export async function GET(request:Request,{params}:{params:Promise<{id:string}>}){
 const session=await getFleetUser(request);if(!session)return new Response("Unauthorized",{status:401});const {id}=await params,db=getDb();
 const [row]=await db.select({filePath:inspectionPhotos.filePath,mimeType:inspectionPhotos.mimeType,driverId:inspections.driverId,vehicleId:inspections.vehicleId}).from(inspectionPhotos).innerJoin(inspections,eq(inspectionPhotos.inspectionId,inspections.id)).where(eq(inspectionPhotos.id,Number(id))).limit(1);if(!row)return new Response("Not found",{status:404});
 if(session.profile.role==="driver"){const own=Number(session.profile.driver_id);if(row.driverId!==own){const related=(await db.select().from(assignments).where(eq(assignments.vehicleId,row.vehicleId))).some(a=>a.driverId===own);if(!related)return new Response("Forbidden",{status:403})}}
 const root=path.resolve(process.env.UPLOAD_DIR||"/tmp/fleet-inspections"),target=path.resolve(root,row.filePath);if(!target.startsWith(root+path.sep))return new Response("Invalid path",{status:400});try{return new Response(await readFile(target),{headers:{"content-type":row.mimeType,"cache-control":"private, max-age=3600"}})}catch{return new Response("Not found",{status:404})}
}
