import { createArtifact } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';

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

const MAX_BYTES = 5 * 1024 * 1024; // 5MB cap

function deriveTitle(rawTitle, filename) {
  const fromForm = (rawTitle || '').trim();
  if (fromForm) return fromForm.slice(0, 200);
  const base = String(filename || 'artifact').replace(/\.[a-z0-9]+$/i, '');
  return (base || 'artifact').slice(0, 200);
}

export async function POST(req) {
  try {
    await requireSession(req);
    const form = await req.formData();
    const project_id = form.get('project_id');
    const file = form.get('file');
    const titleRaw = form.get('title');

    if (!project_id || typeof project_id !== 'string') {
      return Response.json({ error: 'project_id required' }, { status: 400 });
    }
    if (!file || typeof file === 'string' || typeof file.arrayBuffer !== 'function') {
      return Response.json({ error: 'file required' }, { status: 400 });
    }

    const filename = file.name || 'artifact.html';
    const ext = (filename.match(/\.([a-z0-9]+)$/i) || [, ''])[1].toLowerCase();
    const mime = String(file.type || '').toLowerCase();
    const looksHtml = ext === 'html' || ext === 'htm' || mime === 'text/html';
    if (!looksHtml) {
      return Response.json({ error: 'only .html or .htm files supported' }, { status: 400 });
    }

    const buf = Buffer.from(await file.arrayBuffer());
    if (buf.byteLength > MAX_BYTES) {
      return Response.json({ error: `file exceeds ${MAX_BYTES} bytes` }, { status: 413 });
    }
    const content = buf.toString('utf8');
    const title = deriveTitle(titleRaw, filename);

    const result = createArtifact({ title, kind: 'html', content, project_id });
    return Response.json(result, { status: 201 });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ error: err?.message || 'upload failed' }, { status: 400 });
  }
}
