import { eq } from "drizzle-orm";
import { auth } from "@/core/auth/auth";
import { hasPlatformAdminAccess } from "@/core/authorization/authorize";
import { getDb } from "@/core/db/client";
import { tenantUsers, users } from "@/core/db/schema";

/**
 * Resolve landing path from DB by email.
 * Use this right after signIn — auth() may not see the new session cookie yet
 * in the same server-action request.
 */
export async function getPostLoginPathForEmail(email: string): Promise<string> {
  const db = getDb();
  const normalized = email.trim().toLowerCase();

  const [user] = await db
    .select({
      id: users.id,
      platformRole: users.platformRole,
    })
    .from(users)
    .where(eq(users.email, normalized))
    .limit(1);

  if (!user) {
    return "/?auth=login";
  }

  if (
    hasPlatformAdminAccess({
      userId: user.id,
      platformRole: user.platformRole,
      tenantMemberships: [],
    })
  ) {
    return "/admin";
  }

  const memberships = await db
    .select({ status: tenantUsers.status })
    .from(tenantUsers)
    .where(eq(tenantUsers.userId, user.id));

  if (memberships.some((m) => m.status === "active")) {
    return "/dashboard";
  }

  return "/register";
}

/**
 * Decide where a signed-in user should land (session-based).
 * Prefer getPostLoginPathForEmail immediately after credentials sign-in.
 */
export async function getPostLoginPath(): Promise<string> {
  const session = await auth();
  if (!session?.user?.id) {
    return "/?auth=login";
  }

  if (session.user.email) {
    return getPostLoginPathForEmail(session.user.email);
  }

  const principal = {
    userId: session.user.id,
    platformRole: session.user.platformRole,
    tenantMemberships: session.user.tenantMemberships ?? [],
  };

  if (hasPlatformAdminAccess(principal)) {
    return "/admin";
  }

  if (principal.tenantMemberships.some((m) => m.status === "active")) {
    return "/dashboard";
  }

  return "/register";
}
