import { cache } from "react";
import { cookies, headers } from "next/headers";
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { prisma } from "@/lib/db";
import { env } from "@/lib/env";
import type { Role } from "@prisma/client";

/**
 * Session-based authentication.
 *
 * A random 256-bit token is issued to the browser in an httpOnly cookie. Only
 * the SHA-256 digest of that token is persisted, so a database leak does not
 * hand an attacker usable sessions. Sessions are server-revocable and expire
 * both on an absolute deadline and are refreshed on activity.
 */

const TOKEN_BYTES = 32;

function hashToken(token: string): string {
  return createHash("sha256").update(token).digest("hex");
}

export interface SessionUser {
  id: string;
  username: string;
  fullName: string;
  role: Role;
  status: string;
  avatarUrl: string | null;
  email: string | null;
  xp: number;
  level: number;
}

export interface IssuedSession {
  token: string;
  expiresAt: Date;
}

/** Create a session row and return the raw token to place in the cookie. */
export async function createSession(userId: string): Promise<IssuedSession> {
  const token = randomBytes(TOKEN_BYTES).toString("base64url");
  const expiresAt = new Date(Date.now() + env.sessionTtlMs);

  let ipAddress: string | null = null;
  let userAgent: string | null = null;
  try {
    const headerList = await headers();
    ipAddress =
      headerList.get("x-forwarded-for")?.split(",")[0]?.trim() ??
      headerList.get("x-real-ip") ??
      null;
    userAgent = headerList.get("user-agent");
  } catch {
    // `headers()` is unavailable outside a request scope (e.g. seed scripts).
  }

  await prisma.session.create({
    data: {
      tokenHash: hashToken(token),
      userId,
      expiresAt,
      ipAddress,
      userAgent: userAgent?.slice(0, 500) ?? null,
    },
  });

  await prisma.user.update({
    where: { id: userId },
    data: { lastLoginAt: new Date() },
  });

  return { token, expiresAt };
}

/** Resolve the user behind a raw token, or null when invalid/expired. */
export async function resolveSession(token: string | undefined | null): Promise<SessionUser | null> {
  if (!token) return null;

  const session = await prisma.session.findUnique({
    where: { tokenHash: hashToken(token) },
    select: {
      id: true,
      expiresAt: true,
      lastSeen: true,
      user: {
        select: {
          id: true,
          username: true,
          fullName: true,
          role: true,
          status: true,
          avatarUrl: true,
          email: true,
          xp: true,
          level: true,
        },
      },
    },
  });

  if (!session) return null;

  if (session.expiresAt.getTime() < Date.now()) {
    await prisma.session.delete({ where: { id: session.id } }).catch(() => {});
    return null;
  }

  if (session.user.status !== "ACTIVE") {
    return null;
  }

  // Refresh "last seen" at most once an hour to avoid a write per request.
  if (Date.now() - session.lastSeen.getTime() > 60 * 60 * 1000) {
    await prisma.session
      .update({ where: { id: session.id }, data: { lastSeen: new Date() } })
      .catch(() => {});
  }

  return session.user as SessionUser;
}

/**
 * Read the current session cookie and resolve its user.
 *
 * Memoised per request: a page body, its `generateMetadata`, and the dashboard
 * layout all ask for the same session, and this collapses those into one query.
 * Safe to cache because every action that revokes sessions redirects to
 * `/login` instead of re-reading the session afterwards.
 */
export const getSessionUser = cache(async (): Promise<SessionUser | null> => {
  const store = await cookies();
  const token = store.get(env.AUTH_COOKIE_NAME)?.value;
  return resolveSession(token);
});

export function sessionCookieSettings(expiresAt: Date) {
  return {
    httpOnly: true,
    sameSite: "lax" as const,
    secure: env.isProduction,
    path: "/",
    expires: expiresAt,
  };
}

/** Persist the session token in the httpOnly cookie. */
export async function setSessionCookie(token: string, expiresAt: Date): Promise<void> {
  const store = await cookies();
  store.set(env.AUTH_COOKIE_NAME, token, sessionCookieSettings(expiresAt));
}

/** Remove the session cookie from the browser. */
export async function clearSessionCookie(): Promise<void> {
  const store = await cookies();
  store.delete(env.AUTH_COOKIE_NAME);
}

export async function destroySession(token: string | undefined | null): Promise<void> {
  if (!token) return;
  await prisma.session
    .deleteMany({ where: { tokenHash: hashToken(token) } })
    .catch(() => {});
}

export async function destroyAllSessionsForUser(userId: string): Promise<void> {
  await prisma.session.deleteMany({ where: { userId } });
}

/** Housekeeping: drop expired rows. Safe to call opportunistically. */
export async function pruneExpiredSessions(): Promise<number> {
  const result = await prisma.session.deleteMany({
    where: { expiresAt: { lt: new Date() } },
  });
  return result.count;
}

export function constantTimeEquals(a: string, b: string): boolean {
  const bufA = Buffer.from(a);
  const bufB = Buffer.from(b);
  if (bufA.length !== bufB.length) return false;
  return timingSafeEqual(bufA, bufB);
}
