import { createServerFn } from "@tanstack/react-start";
import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware";
import { services } from "@/lib/services";

export const ADMIN_EMAIL = "flexflares@admin.flexflares.app";

// Admin: delete a user account (auth + cascades to profile/roles).
export const adminDeleteUser = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .inputValidator((d: { userId: string }) => d)
  .handler(async ({ data, context }) => {
    const { data: isAdmin } = await context.supabase.rpc("has_role", {
      _user_id: context.userId,
      _role: "admin",
    });
    if (!isAdmin) throw new Error("Forbidden");
    if (data.userId === context.userId) throw new Error("Cannot delete your own admin account");
    const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
    const { error } = await supabaseAdmin.auth.admin.deleteUser(data.userId);
    if (error) throw new Error(error.message);
    return { ok: true as const };
  });

// Admin: refresh + re-index AI knowledge base. The chat route reads sources
// live per request, so this verifies connectivity and returns fresh counts.
export const refreshAiKnowledge = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const { data: isAdmin } = await context.supabase.rpc("has_role", {
      _user_id: context.userId,
      _role: "admin",
    });
    if (!isAdmin) throw new Error("Forbidden");

    const [faqs, activeFaqs, anns, settings] = await Promise.all([
      context.supabase.from("ai_faqs").select("id", { count: "exact", head: true }),
      context.supabase.from("ai_faqs").select("id", { count: "exact", head: true }).eq("active", true),
      context.supabase.from("announcements").select("id", { count: "exact", head: true }),
      context.supabase.from("business_settings").select("ai_enabled").eq("id", 1).maybeSingle(),
    ]);

    return {
      ok: true as const,
      indexedAt: new Date().toISOString(),
      counts: {
        services: services.length,
        faqs: faqs.count ?? 0,
        activeFaqs: activeFaqs.count ?? 0,
        announcements: anns.count ?? 0,
      },
      aiEnabled: (settings.data as { ai_enabled?: boolean } | null)?.ai_enabled ?? true,
    };
  });