import { initDb } from "@/lib/db";
import { FEATURES } from "@/config/features";
import type { ActiveMode, UserCapabilities } from "@/types/participant";

const PARTICIPANT_USABLE_STATUSES = new Set(["active", "paused"]);

/**
 * Resolve the mode the user should land in. A stored preference is only
 * honoured if the matching capability still exists.
 */
export function resolveActiveMode(
  preferred: ActiveMode | null | undefined,
  hasCreator: boolean,
  hasParticipant: boolean
): ActiveMode {
  if (preferred === "participant" && hasParticipant) return "participant";
  if (preferred === "creator" && hasCreator) return "creator";
  if (hasCreator) return "creator";
  if (hasParticipant) return "participant";
  return "creator";
}

/** Server-derived capabilities — never trust these from the browser. */
export async function loadUserCapabilities(user: {
  id: string;
  workspaceId: string | null;
}): Promise<UserCapabilities> {
  const hasCreatorCapability = Boolean(user.workspaceId);

  if (!FEATURES.participantPlatform) {
    return {
      activeMode: "creator",
      hasCreatorCapability,
      hasParticipantCapability: false,
      participantProfileId: null,
    };
  }

  const { ParticipantProfile, UserPreference } = initDb();
  const [profile, prefs] = await Promise.all([
    ParticipantProfile.findOne({
      where: { userId: user.id },
      attributes: ["id", "status"],
    }),
    UserPreference.findOne({
      where: { userId: user.id },
      attributes: ["activeMode"],
    }),
  ]);

  const hasParticipantCapability = Boolean(
    profile && PARTICIPANT_USABLE_STATUSES.has(profile.status)
  );

  return {
    activeMode: resolveActiveMode(
      prefs?.activeMode,
      hasCreatorCapability,
      hasParticipantCapability
    ),
    hasCreatorCapability,
    hasParticipantCapability,
    participantProfileId: hasParticipantCapability ? profile!.id : null,
  };
}

export function landingPathForMode(mode: ActiveMode): string {
  return mode === "participant" ? "/participant" : "/app/dashboard";
}
