import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
import { and, 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.
 *
 * Resolution order:
 *  1. `preferences.defaultPortId` - last port the user worked in, written
 *     by the port-switcher. Only honoured if the user still has access
 *     (preference may be stale after a role revoke or port archive).
 *  2. Super-admin → first port alphabetically. Other users → first
 *     `user_port_roles` row.
 */
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),
  });

  const lastPortId = (profile?.preferences as { defaultPortId?: string } | null)?.defaultPortId;
  let slug: string | undefined;

  if (lastPortId) {
    // Verify access before honouring the preference - a stale id (port
    // archived, role revoked) shouldn't strand the user on a 403.
    if (profile?.isSuperAdmin) {
      const port = await db.query.ports.findFirst({ where: eq(portsTable.id, lastPortId) });
      slug = port?.slug;
    } else {
      const role = await db.query.userPortRoles.findFirst({
        where: and(eq(userPortRoles.userId, session.user.id), eq(userPortRoles.portId, lastPortId)),
        with: { port: true },
      });
      slug = role?.port.slug;
    }
  }

  if (!slug) {
    if (profile?.isSuperAdmin) {
      const first = await db.query.ports.findFirst({ orderBy: portsTable.createdAt });
      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);
}
