import { NextResponse } from 'next/server';
import { mkdir, writeFile } from 'fs/promises';
import path from 'path';
import { requireAdmin } from '@/lib/require-admin';

// Local uploads for the admin dashboard: stores files under public/uploads
// and serves them at /uploads/<name>. Only admins may upload.
// Accepts a single file per request under the "file" field (multipart/form-data).
// NOTE: not a durable CDN — see next.config remotePatterns / README for options.

const MAX_SIZE = 5 * 1024 * 1024; // 5 MB
const ALLOWED = new Map([
  ['image/jpeg', '.jpg'],
  ['image/png', '.png'],
  ['image/webp', '.webp'],
  ['image/gif', '.gif'],
  ['image/svg+xml', '.svg'],
  ['image/avif', '.avif']
]);

export async function POST(req: Request) {
  const { response } = await requireAdmin();
  if (response) return response;

  const form = await req.formData().catch(() => null);
  const file = form?.get('file');
  if (!(file instanceof File)) {
    return NextResponse.json({ error: 'no_file' }, { status: 400 });
  }
  if (file.size > MAX_SIZE) {
    return NextResponse.json({ error: 'file_too_large' }, { status: 413 });
  }

  const ext = ALLOWED.get(file.type);
  if (!ext) {
    return NextResponse.json({ error: 'unsupported_type' }, { status: 415 });
  }

  const name = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}${ext}`;
  const bytes = Buffer.from(await file.arrayBuffer());

  const dir = path.join(process.cwd(), 'public', 'uploads');
  await mkdir(dir, { recursive: true });
  await writeFile(path.join(dir, name), bytes);

  return NextResponse.json({ url: `/uploads/${name}` }, { status: 201 });
}