import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getAuthenticatedAdmin } from '@/lib/admin-auth';
import { ensureRestaurantStats } from '@/lib/restaurant-stats';
import { parseBody, sponsorCreateSchema } from '@/lib/validation';
import { buildAddressDisplay } from '@/lib/format-address';

// BUGFIX: GET lieferte bisher NUR die rohen sponsored_restaurants-Spalten,
// nie impressions/yesSwipes/matches. Die Sponsoring-Seite ruft NIE
// /api/admin/stats auf (nur /api/admin/sponsors), daher blieben die Swipe-
// Stats auf den Sponsor-Karten permanent bei 0/undefined - unabhaengig vom
// v7-Verknuepfungs-Fix. Jetzt: LEFT JOIN auf restaurant_stats, exakt wie in
// stats/route.ts (sponsorCampaignPerformance), damit beide Endpunkte
// dieselben echten Zahlen liefern.
export async function GET() {
  const admin = await getAuthenticatedAdmin();
  if (!admin) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });

  const db = getDb();
  ensureRestaurantStats(db);

  const sponsors = db.prepare(`
    SELECT
      sr.*,
      COALESCE(rs.impressions, 0) AS impressions,
      COALESCE(rs.yes_swipes, 0) AS yesSwipes,
      COALESCE(rs.matches, 0) AS matches
    FROM sponsored_restaurants sr
    LEFT JOIN restaurant_stats rs ON rs.restaurant_id = sr.restaurant_id
    ORDER BY sr.priority DESC, sr.created_at DESC
  `).all();

  return NextResponse.json({ sponsors });
}

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

  const parsed = await parseBody(req, sponsorCreateSchema);
  if (!parsed.success) return parsed.response;

  const {
    name, imageUrl, address, city, postalCode, lat, lon,
    filterCuisineTags, discountText, priority,
    active, activeFrom, activeUntil,
    disclaimerText, openingHoursRaw, reservationUrl,
    lieferandoUrl,
    restaurantId,
  } = parsed.data;

  const db = getDb();
  const result = db.prepare(
    `INSERT INTO sponsored_restaurants
     (name, image_url, address, city, postal_code, lat, lon, filter_cuisine_tags, discount_text, priority, active, active_from, active_until, disclaimer_text, opening_hours_raw, reservation_url, lieferando_url, restaurant_id)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
  ).run(
    name,
    imageUrl ?? null,
    address ?? null,
    city,
    postalCode ?? null,
    lat ?? null,
    lon ?? null,
    filterCuisineTags ? JSON.stringify(filterCuisineTags) : null,
    discountText ?? null,
    priority ?? 0,
    active === false ? 0 : 1,
    activeFrom ?? null,
    activeUntil ?? null,
    disclaimerText ?? null,
    openingHoursRaw ?? null,
    reservationUrl ?? null,
    lieferandoUrl ?? null,
    restaurantId ?? null
  );

  // Bei direkter Verknuepfung mit einem bestehenden Restaurant die Adresse/PLZ
  // dort direkt mit synchronisieren, damit Matches/Polls konsistent sind.
  if (restaurantId) {
    const cuisineValue = filterCuisineTags ? filterCuisineTags.join(', ') : null;
    db.prepare(`
      UPDATE restaurants SET
        name = ?, lat = ?, lon = ?, address = ?, postal_code = ?,
        admin_image_url = COALESCE(?, admin_image_url),
        image_source_used = CASE WHEN ? IS NOT NULL THEN 'admin' ELSE image_source_used END,
        cuisine = COALESCE(?, cuisine),
        opening_hours_raw = COALESCE(?, opening_hours_raw)
      WHERE id = ?
    `).run(
      name,
      lat ?? null,
      lon ?? null,
      buildAddressDisplay(address, postalCode, city),
      postalCode ?? null,
      imageUrl ?? null,
      imageUrl ?? null,
      cuisineValue,
      openingHoursRaw ?? null,
      restaurantId
    );
  }

  return NextResponse.json({ id: result.lastInsertRowid });
}
