import { NextResponse } from 'next/server' import { readFile } from 'node:fs/promises' import path from 'node:path' import { getPayload } from 'payload' import configPromise from '@payload-config' import { FILES_DIR } from '@/collections/Files' import { getViewer } from '@/lib/viewer' import { freeEarlyAccess } from '@/lib/launch' export const dynamic = 'force-dynamic' type FileDoc = { id: number; access: 'free' | 'vip'; filename: string; mimeType: string } /* GET /api/files/[id] — per-post work files, gated per file. `free` streams to anyone; `vip` requires a signed-in vip/admin (same style as the comments route). The Files collection read rule is defense in depth; this route is the enforcement point for the bytes. */ export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) { const { id } = await ctx.params const payload = await getPayload({ config: configPromise }) let doc: FileDoc | null = null try { doc = (await payload.findByID({ collection: 'files', id, depth: 0, overrideAccess: true })) as unknown as FileDoc } catch { doc = null // unknown id / DB error → not found } if (!doc?.filename) return NextResponse.json({ error: 'الملف غير موجود.' }, { status: 404 }) // L-02: all files open during free early access (owner curates file // access in the admin; ALL vip files download while billing is off). // Viewer checks apply only when billing is enabled. if (doc.access === 'vip' && !freeEarlyAccess()) { const viewer = await getViewer() if (!viewer) return NextResponse.json({ error: 'سجّل الدخول لتنزيل الملفات.' }, { status: 401 }) if (viewer.role !== 'vip' && viewer.role !== 'admin') { return NextResponse.json({ error: 'التنزيل متاح لأعضاء العضوية.' }, { status: 403 }) } } try { const buf = await readFile(path.join(FILES_DIR, doc.filename)) return new NextResponse(new Uint8Array(buf), { headers: { 'Content-Type': doc.mimeType, 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(doc.filename)}`, }, }) } catch { // Row exists but the file is missing on disk — do not leak a fake download. return NextResponse.json({ error: 'الملف غير موجود.' }, { status: 404 }) } }