import type { FastifyPluginAsync } from "fastify";
import QRCode from "qrcode";
import { requireAuth, requireRestaurantMember } from "../lib/auth.js";
import { env } from "../env.js";
import { supabase } from "../lib/supabase.js";

// QR image encodes a stable /q/:id redirect, never the restaurant's current
// domain directly — so republishing the menu or moving to a custom domain
// never invalidates a printed QR code (PRD §12).
export const qrRoutes: FastifyPluginAsync = async (app) => {
  app.post("/restaurants/:id/qr", async (req, reply) => {
    const userId = await requireAuth(req, reply);
    if (!userId || !supabase) return;

    const { id: restaurantId } = req.params as { id: string };
    const isMember = await requireRestaurantMember(userId, restaurantId);
    if (!isMember) return reply.code(403).send({ message: "forbidden" });

    const { data: restaurant, error: restaurantError } = await supabase
      .from("restaurants")
      .select("slug")
      .eq("id", restaurantId)
      .single();

    if (restaurantError || !restaurant) {
      return reply.code(404).send({ message: "restaurant not found" });
    }

    const webBaseUrl = env.PUBLIC_WEB_URL || "http://localhost:3000";
    const targetUrl = `${webBaseUrl}/menu/${restaurant.slug}`;

    const { data: existing } = await supabase
      .from("qr_codes")
      .select("id")
      .eq("restaurant_id", restaurantId)
      .maybeSingle();

    if (existing) {
      await supabase
        .from("qr_codes")
        .update({ target_url: targetUrl })
        .eq("id", existing.id);
    } else {
      await supabase
        .from("qr_codes")
        .insert({ restaurant_id: restaurantId, target_url: targetUrl });
    }

    // QR image directly encodes the clean restaurant name URL (e.g. /menu/kebapci-ahmet)
    const [pngBuffer, svg] = await Promise.all([
      QRCode.toBuffer(targetUrl, { type: "png", width: 1024, margin: 2 }),
      QRCode.toString(targetUrl, { type: "svg", margin: 2 }),
    ]);

    return reply.send({
      id: restaurant.slug,
      redirectUrl: targetUrl,
      targetUrl,
      pngBase64: pngBuffer.toString("base64"),
      svg,
    });
  });
};
