import { initDb } from "@/lib/db";
import { requireActiveUser } from "@/lib/auth/verify-session-user";
import type { UserRole } from "@/types";

/**
 * Resolve where a logged-in user should land — only if JWT still matches
 * an active DB user with a usable workspace. Returns null when the session
 * cookie is stale / invalid (caller should force logout).
 */
export async function getValidatedPostAuthPath(
  userId: string
): Promise<string | null> {
  try {
    const user = await requireActiveUser(userId);
    if (!user) return null;

    const role = user.role as UserRole;

    if (role === "super_admin" && !user.workspaceId) {
      return "/admin/overview";
    }

    if (!user.workspaceId) {
      return role === "client" ? "/onboarding" : "/login";
    }

    const { Workspace } = initDb();
    const workspace = await Workspace.findByPk(user.workspaceId);
    if (!workspace || workspace.isSuspended) {
      return null;
    }

    return "/app/dashboard";
  } catch {
    // DB / pool errors must not bounce login↔app forever.
    return null;
  }
}

/** Send the browser to clear the session cookie, then to login. */
export function loginRedirectUrl(reason?: string): string {
  const login = reason
    ? `/login?error=${encodeURIComponent(reason)}`
    : "/login";
  return `/api/auth/force-logout?callbackUrl=${encodeURIComponent(login)}`;
}
