import { NextResponse } from 'next/server';
import { recordEvent } from '@/lib/auditDb';
import { saveUploadedImage } from '@/lib/storage';
import type { UploadImageResponse, UploadedImageRole } from '@/lib/types';

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

const ROLES: UploadedImageRole[] = [
  'reference',
  'subject',
  'view-front',
  'view-back',
  'view-left',
  'view-right',
  'view-top',
  'view-bottom',
  'accessory-isolated',
  'accessory-named',
];

function isFileLike(value: FormDataEntryValue | null): value is File {
  return !!value && typeof value === 'object' && 'arrayBuffer' in value && 'type' in value && 'name' in value;
}

export async function POST(req: Request) {
  const form = await req.formData();
  const file = form.get('image') ?? form.get('file');
  const roleValue = String(form.get('role') ?? 'reference');
  const role = ROLES.includes(roleValue as UploadedImageRole) ? roleValue as UploadedImageRole : 'reference';
  const accessoryName = String(form.get('accessoryName') ?? '').trim() || undefined;
  const needsCleanup = String(form.get('needsCleanup') ?? 'true') !== 'false';

  if (!isFileLike(file)) {
    return NextResponse.json({ error: 'image file required' }, { status: 400 });
  }
  if (!file.type.startsWith('image/')) {
    return NextResponse.json({ error: 'only image uploads are supported' }, { status: 400 });
  }
  if (file.size > 12 * 1024 * 1024) {
    return NextResponse.json({ error: 'image must be <= 12MB' }, { status: 400 });
  }

  const uploadedImage = await saveUploadedImage({
    buffer: Buffer.from(await file.arrayBuffer()),
    mimeType: file.type,
    originalFilename: file.name,
    role,
    accessoryName,
    needsCleanup,
  });
  recordEvent({
    action: 'upload.completed',
    targetType: 'upload',
    targetId: uploadedImage.id,
    status: 'ok',
    metadata: { filename: uploadedImage.filename, originalFilename: uploadedImage.originalFilename, role, size: file.size },
  });

  return NextResponse.json({ uploadedImage } satisfies UploadImageResponse);
}
