import { NextRequest, NextResponse } from 'next/server';
import { getAuthenticatedAdmin } from '@/lib/admin-auth';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';
import { randomUUID } from 'crypto';

const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
const MAX_SIZE_BYTES = 5 * 1024 * 1024;

type ImageExt = 'jpg' | 'png' | 'webp';

function detectImageType(buffer: Buffer): ImageExt | null {
  if (buffer.length < 12) return null;

  // JPEG: FF D8 FF
  if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
    return 'jpg';
  }

  // PNG: 89 50 4E 47 0D 0A 1A 0A
  if (
    buffer[0] === 0x89 &&
    buffer[1] === 0x50 &&
    buffer[2] === 0x4e &&
    buffer[3] === 0x47 &&
    buffer[4] === 0x0d &&
    buffer[5] === 0x0a &&
    buffer[6] === 0x1a &&
    buffer[7] === 0x0a
  ) {
    return 'png';
  }

  // WebP: RIFF....WEBP
  const isRiff = buffer.slice(0, 4).toString('ascii') === 'RIFF';
  const isWebp = buffer.slice(8, 12).toString('ascii') === 'WEBP';
  if (isRiff && isWebp) {
    return 'webp';
  }

  return null;
}

export async function POST(req: NextRequest) {
  const admin = await getAuthenticatedAdmin();
  if (!admin) {
    return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
  }

  const formData = await req.formData();
  const file = formData.get('image') as File | null;
  if (!file) {
    return NextResponse.json({ error: 'Kein Bild uebermittelt' }, { status: 400 });
  }

  if (!ALLOWED_TYPES.includes(file.type)) {
    return NextResponse.json({ error: 'Nur JPEG, PNG oder WebP erlaubt' }, { status: 400 });
  }

  if (file.size > MAX_SIZE_BYTES) {
    return NextResponse.json({ error: 'Bild zu gross (max. 5 MB)' }, { status: 400 });
  }

  const buffer = Buffer.from(await file.arrayBuffer());
  const detectedExt = detectImageType(buffer);
  if (!detectedExt) {
    return NextResponse.json({ error: 'Datei ist kein gueltiges Bild (JPEG/PNG/WebP)' }, { status: 400 });
  }

  const filename = `${randomUUID()}.${detectedExt}`;
  const uploadDir = path.join(process.cwd(), 'uploads', 'sponsors');
  await mkdir(uploadDir, { recursive: true });
  await writeFile(path.join(uploadDir, filename), buffer);

  const publicPath = `/api/uploads/sponsors/${filename}`;
  return NextResponse.json({ url: publicPath });
}
