<script setup lang="ts">
// Vue port of React ProtectedAdminRoute.
// Usage: wrap an admin page's content, e.g. in AdminImport.vue:
//   <ProtectedAdminRoute><AdminImportContent /></ProtectedAdminRoute>
// It redirects to /admin/login (router.replace) when the user is not an admin.
// (See report for the alternative router navigation-guard wiring.)
import { ref, watch, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { supabase } from "@/integrations/supabase/client";
import { Loader2 } from "lucide-vue-next";

const router = useRouter();

const loading = ref(true);
const authorized = ref(false);
let initialCheckDone = false;
let unsubscribe: (() => void) | undefined;

const checkAdmin = async (userId: string) => {
  const { data: roleRow } = await supabase
    .from("user_roles")
    .select("role")
    .eq("user_id", userId)
    .eq("role", "admin")
    .maybeSingle();
  authorized.value = !!roleRow;
  loading.value = false;
};

onMounted(() => {
  // Listen to auth state changes — but ignore null session until initial check is done
  const { data } = supabase.auth.onAuthStateChange((_event, session) => {
    if (session?.user) {
      initialCheckDone = true;
      checkAdmin(session.user.id);
    } else if (initialCheckDone) {
      // Only redirect if we already confirmed the initial state
      authorized.value = false;
      loading.value = false;
    }
  });
  unsubscribe = () => data.subscription.unsubscribe();

  // Initial session check — this is the source of truth
  supabase.auth.getSession().then(({ data: { session } }) => {
    initialCheckDone = true;
    if (session?.user) {
      checkAdmin(session.user.id);
    } else {
      authorized.value = false;
      loading.value = false;
    }
  });
});

onUnmounted(() => {
  unsubscribe?.();
});

// Redirect once we know the user is not authorized (equivalent of <Navigate to="/admin/login" replace />)
watch([loading, authorized], ([l, a]) => {
  if (!l && !a) {
    router.replace("/admin/login");
  }
});
</script>

<template>
  <div v-if="loading" class="min-h-screen flex items-center justify-center">
    <Loader2 class="w-8 h-8 animate-spin text-muted-foreground" />
  </div>
  <slot v-else-if="authorized" />
</template>
