import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
import { eq } from 'drizzle-orm';

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { ports as portsTable } from '@/lib/db/schema/ports';
import { userPortRoles, userProfiles } from '@/lib/db/schema/users';

/**
 * Plain `/dashboard` lands users into their default port's dashboard. Used
 * by post-login redirects and any code that doesn't yet know the active
 * port slug.
 */
export default async function DashboardRedirectPage() {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session?.user) redirect('/login');

  const profile = await db.query.userProfiles.findFirst({
    where: eq(userProfiles.userId, session.user.id),
  });

  let slug: string | undefined;
  if (profile?.isSuperAdmin) {
    const first = await db.query.ports.findFirst({ orderBy: portsTable.name });
    slug = first?.slug;
  } else {
    const role = await db.query.userPortRoles.findFirst({
      where: eq(userPortRoles.userId, session.user.id),
      with: { port: true },
    });
    slug = role?.port.slug;
  }

  if (!slug) redirect('/login?error=no-port-access');
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  redirect(`/${slug}/dashboard` as any);
}
