import { redirect } from "next/navigation";
import { initDb } from "@/lib/db";
import { requireAuth } from "@/lib/auth/require-auth";
import { loginRedirectUrl } from "@/lib/auth/post-auth-path";
import { FEATURES } from "@/config/features";

/**
 * Require an active (or paused) participant profile. Always re-reads the
 * profile from the DB — the JWT capability flag is only a routing hint.
 */
export async function requireParticipantContext() {
  if (!FEATURES.participantPlatform) {
    redirect("/app/dashboard");
  }

  const session = await requireAuth();

  let profile;
  try {
    const { ParticipantProfile } = initDb();
    profile = await ParticipantProfile.findOne({
      where: { userId: session.user.id },
    });
  } catch {
    redirect(loginRedirectUrl("DatabaseError"));
  }

  if (!profile || (profile.status !== "active" && profile.status !== "paused")) {
    redirect("/onboarding?intent=participate");
  }

  return {
    session,
    userId: session.user.id,
    profile,
    hasCreatorCapability: Boolean(session.user.workspaceId),
  };
}

/** For server actions: returns null instead of redirecting. */
export async function getActiveParticipantProfile(userId: string) {
  if (!FEATURES.participantPlatform) return null;
  const { ParticipantProfile } = initDb();
  const profile = await ParticipantProfile.findOne({ where: { userId } });
  if (!profile || profile.status !== "active") return null;
  return profile;
}
