import type { FastifyPluginAsync } from "fastify";
import { requireAuth } from "../lib/auth.js";
import { supabase } from "../lib/supabase.js";

// Mobile cold-start rehydration: "does this signed-in user already own a
// restaurant?" — kept behind the API (not a direct Supabase read from
// mobile) so ownership resolution stays in one place (PRD §23, §33).
export const meRoutes: FastifyPluginAsync = async (app) => {
  app.get("/me/restaurant", async (req, reply) => {
    const userId = await requireAuth(req, reply);
    if (!userId || !supabase) return;

    const { data: membership } = await supabase
      .from("restaurant_members")
      .select("restaurant_id")
      .eq("user_id", userId)
      .limit(1)
      .maybeSingle();

    if (!membership) return reply.send({ restaurant: null });

    const { data: restaurant } = await supabase
      .from("restaurants")
      .select("id, name, slug, locations(id, menus(id))")
      .eq("id", membership.restaurant_id)
      .single();

    return reply.send({ restaurant });
  });
};
