import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getAuthenticatedAdmin } from '@/lib/admin-auth';

// Admin-Override fuer einen gecachten Restaurant-Eintrag: Name, Kueche,
// Fast-Food-Flag und ein manuell hinterlegtes Bild (admin_image_url).
// admin_image_url wird vom Deck-Builder bevorzugt, siehe lib/image-resolver.ts.
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const admin = await getAuthenticatedAdmin();
  if (!admin) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });

  const { id } = await params;
  const restaurantId = Number(id);
  if (!Number.isInteger(restaurantId)) {
    return NextResponse.json({ error: 'Ungueltige ID' }, { status: 400 });
  }

  let body: any;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: 'Ungueltiger Body' }, { status: 400 });
  }
  if (!body || typeof body !== 'object') {
    return NextResponse.json({ error: 'Ungueltiger Body' }, { status: 400 });
  }

  const db = getDb();
  const existing = db.prepare('SELECT * FROM restaurants WHERE id = ?').get(restaurantId) as any;
  if (!existing) return NextResponse.json({ error: 'Restaurant nicht gefunden' }, { status: 404 });

  const { name, cuisine, adminImageUrl, isFastFood } = body;

  const nextName = typeof name === 'string' && name.trim() ? name.trim() : existing.name;
  const nextCuisine = typeof cuisine === 'string' ? cuisine.trim() : existing.cuisine;
  const nextFastFood = isFastFood !== undefined ? (isFastFood ? 1 : 0) : existing.is_fast_food;

  let adminImage: string | null = existing.admin_image_url;
  let imageSource: string | null = existing.image_source_used;
  if (adminImageUrl !== undefined) {
    if (typeof adminImageUrl === 'string' && adminImageUrl.trim()) {
      adminImage = adminImageUrl.trim();
      imageSource = 'admin';
    } else {
      adminImage = null;
      imageSource = 'none';
    }
  }

  db.prepare(
    `UPDATE restaurants SET
       name = ?, cuisine = ?, is_fast_food = ?, admin_image_url = ?, image_source_used = ?,
       updated_at = datetime('now')
     WHERE id = ?`
  ).run(nextName, nextCuisine, nextFastFood, adminImage, imageSource, restaurantId);

  return NextResponse.json({ success: true });
}
