import { requireSession } from '@/lib/auth.js';
import { saveUpload, isAllowedAttachment, MAX_UPLOAD_BYTES, MAX_ATTACHMENTS } from '@/lib/chat-uploads.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

// Accepts multipart/form-data with one or more `files` fields. Persists each to
// the local uploads store and returns opaque attachment refs the chat composer
// echoes back on the next send. Bytes never leave the machine.
export async function POST(req) {
  try {
    await requireSession(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }

  let form;
  try {
    form = await req.formData();
  } catch {
    return Response.json({ error: 'expected multipart/form-data' }, { status: 400 });
  }

  const files = form.getAll('files').filter(f => f && typeof f.arrayBuffer === 'function');
  if (!files.length) return Response.json({ error: 'no files' }, { status: 400 });
  if (files.length > MAX_ATTACHMENTS) {
    return Response.json({ error: `max ${MAX_ATTACHMENTS} files per message` }, { status: 400 });
  }

  const attachments = [];
  for (const file of files) {
    const name = file.name || 'file';
    const mime = file.type || 'application/octet-stream';
    if (!isAllowedAttachment(mime, name)) {
      return Response.json({ error: `unsupported file type: ${name}` }, { status: 415 });
    }
    const buffer = Buffer.from(await file.arrayBuffer());
    if (buffer.length > MAX_UPLOAD_BYTES) {
      return Response.json({ error: `${name} exceeds ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB limit` }, { status: 413 });
    }
    try {
      attachments.push(saveUpload({ buffer, name, mime }));
    } catch (err) {
      return Response.json({ error: `${name}: ${err.message}` }, { status: 400 });
    }
  }

  return Response.json({ attachments });
}
