import { cookies } from 'next/headers';
import { eq } from 'drizzle-orm';
import { db } from '@/db';
import { sessions } from '@/db/schema';
import { getUserById } from '@/db/auth-queries';
import {
  generateSessionToken,
  hashSessionToken,
  isSessionExpired,
  sessionExpiry,
} from './tokens';
import type { AuthUser } from './authz';

const COOKIE = 'session';

export async function createSession(userId: string): Promise<void> {
  const token = generateSessionToken();
  await db.insert(sessions).values({
    userId,
    tokenHash: hashSessionToken(token),
    expiresAt: sessionExpiry(),
  });
  const store = await cookies();
  store.set(COOKIE, token, {
    httpOnly: true,
    secure: true,
    sameSite: 'lax',
    path: '/',
    expires: sessionExpiry(),
  });
}

export async function destroySession(): Promise<void> {
  const store = await cookies();
  const token = store.get(COOKIE)?.value;
  if (token) {
    await db.delete(sessions).where(eq(sessions.tokenHash, hashSessionToken(token)));
    store.delete(COOKIE);
  }
}

export async function getSessionUser(): Promise<AuthUser | null> {
  const store = await cookies();
  const token = store.get(COOKIE)?.value;
  if (!token) return null;

  const [session] = await db
    .select()
    .from(sessions)
    .where(eq(sessions.tokenHash, hashSessionToken(token)))
    .limit(1);
  if (!session) return null;

  if (isSessionExpired(session.expiresAt)) {
    await db.delete(sessions).where(eq(sessions.id, session.id));
    return null;
  }

  const user = await getUserById(session.userId);
  if (!user || user.status !== 'activo') return null;

  return {
    id: user.id,
    email: user.email,
    nombre: user.nombre,
    role: user.role,
    tenantId: user.tenantId,
    status: user.status,
  };
}
