import "server-only";

import { cache } from "react";
import { redirect } from "next/navigation";
import { createServerSupabaseClient } from "@/lib/supabase/server";
import { isSupabaseConfigured } from "@/lib/supabase/config";
import type { AppRole, Profile } from "@/types/domain";

export const getCurrentProfile = cache(async (): Promise<Profile | null> => {
  if (!isSupabaseConfigured()) return null;
  const supabase = await createServerSupabaseClient();
  const {
    data: { user }
  } = await supabase.auth.getUser();
  if (!user) return null;

  const { data } = await supabase
    .from("profiles")
    .select("id, role, full_name, phone, login_username, must_change_password, deleted_at, is_active, last_activity_at, created_at, updated_at")
    .eq("id", user.id)
    .single();

  return (data as Profile | null) ?? null;
});

export async function requireProfile(role?: AppRole): Promise<Profile> {
  const profile = await getCurrentProfile();
  const dashboardPath = role === "admin" ? "/admin" : "/donor";
  if (!profile) redirect(`/login?next=${dashboardPath}`);
  if (!profile.is_active) redirect("/login?error=inactive");
  if (role && profile.role !== role) redirect(profile.role === "admin" ? "/admin" : "/donor");
  return profile;
}

export async function getCurrentUserId(): Promise<string | null> {
  if (!isSupabaseConfigured()) return null;
  const supabase = await createServerSupabaseClient();
  const {
    data: { user }
  } = await supabase.auth.getUser();
  return user?.id ?? null;
}
