import { getDb } from './db';
import { buildAddressDisplay } from './format-address';

// Loest eine Karten-ID aus dem Frontend zu einer echten restaurants.id auf.
// Normale Restaurants kommen bereits als Zahl -> direkt zurueckgeben.
// Sponsor-Karten kommen als "sponsor-<id>" -> beim ersten Swipe wird automatisch
// ein zugehoeriger restaurants-Eintrag angelegt (oder wiederverwendet über
// sponsored_restaurants.restaurant_id), damit swipes/matches/vetos ganz normal
// per Foreign Key auf restaurants(id) funktionieren.
export function resolveSponsorToRestaurantId(cardId: number | string): number | null {
  const db = getDb();

  if (typeof cardId === 'number') return cardId;

  const match = /^sponsor-(\d+)$/.exec(cardId);
  if (!match) {
    // Falls schon ein numerischer String reinkommt (z.B. "42"), einfach parsen.
    const parsed = Number(cardId);
    return Number.isFinite(parsed) ? parsed : null;
  }

  // In einer Transaktion aufloesen, damit parallele erste Swipes auf denselben
  // Sponsor nicht mehrfache restaurants-Eintraege erzeugen.
  return db.transaction(() => {
    const sponsorId = Number(match[1]);
    const sponsor = db.prepare('SELECT * FROM sponsored_restaurants WHERE id = ?').get(sponsorId) as any;
    if (!sponsor) return null;

    // Bereits verknuepft? Dann die existierende restaurants-Zeile wiederverwenden.
    if (sponsor.restaurant_id) {
      const existing = db.prepare('SELECT id FROM restaurants WHERE id = ?').get(sponsor.restaurant_id) as any;
      if (existing) return existing.id;
    }

    // Noch keine Verknuepfung -> neuen restaurants-Eintrag anlegen und dauerhaft verknuepfen,
    // damit kuenftige Swipes auf denselben Sponsor die gleiche restaurant_id treffen.
    const cuisineTags: string[] = sponsor.filter_cuisine_tags ? JSON.parse(sponsor.filter_cuisine_tags) : [];
    const fullAddress = buildAddressDisplay(sponsor.address, sponsor.postal_code, sponsor.city);
    const insert = db.prepare(`
      INSERT INTO restaurants (name, lat, lon, address, postal_code, suburb, cuisine, price_rating, is_fast_food, admin_image_url, image_source_used)
      VALUES (?, ?, ?, ?, ?, ?, ?, NULL, 0, ?, 'admin')
    `).run(
      sponsor.name,
      sponsor.lat,
      sponsor.lon,
      fullAddress,
      sponsor.postal_code,
      (sponsor as any).suburb ?? null,
      cuisineTags.join(', ') || null,
      sponsor.image_url
    );

    const newRestaurantId = Number(insert.lastInsertRowid);
    db.prepare('UPDATE sponsored_restaurants SET restaurant_id = ? WHERE id = ?').run(newRestaurantId, sponsorId);

    return newRestaurantId;
  })();
}
