import { create, findOne, deleteWhere, updateById } from '@zen/core/database';
import { generateToken, generateId } from './password.js';

async function createSession(userId, options = {}) {
  const { ipAddress, userAgent } = options;
  const token = generateToken(32);
  const sessionId = generateId();
  const expiresAt = new Date();
  expiresAt.setDate(expiresAt.getDate() + 30);

  const session = await create('zen_auth_sessions', {
    id: sessionId,
    user_id: userId,
    token,
    expires_at: expiresAt,
    ip_address: ipAddress || null,
    user_agent: userAgent || null,
    updated_at: new Date()
  });

  return session;
}

async function validateSession(token) {
  if (!token) return null;

  const session = await findOne('zen_auth_sessions', { token });
  if (!session) return null;

  if (new Date(session.expires_at) < new Date()) {
    await deleteSession(token);
    return null;
  }

  const user = await findOne('zen_auth_users', { id: session.user_id });
  if (!user) {
    await deleteSession(token);
    return null;
  }

  const now = new Date();
  const expiresAt = new Date(session.expires_at);
  const daysUntilExpiry = Math.ceil((expiresAt - now) / (1000 * 60 * 60 * 24));

  let sessionRefreshed = false;
  if (daysUntilExpiry < 20) {
    const newExpiresAt = new Date();
    newExpiresAt.setDate(newExpiresAt.getDate() + 30);
    await updateById('zen_auth_sessions', session.id, {
      expires_at: newExpiresAt,
      updated_at: new Date()
    });
    session.expires_at = newExpiresAt;
    sessionRefreshed = true;
  }

  return { session, user, sessionRefreshed };
}

async function deleteSession(token) {
  return await deleteWhere('zen_auth_sessions', { token });
}

async function deleteUserSessions(userId) {
  return await deleteWhere('zen_auth_sessions', { user_id: userId });
}

async function refreshSession(token) {
  const session = await findOne('zen_auth_sessions', { token });
  if (!session) return null;
  const expiresAt = new Date();
  expiresAt.setDate(expiresAt.getDate() + 30);
  return await updateById('zen_auth_sessions', session.id, {
    expires_at: expiresAt,
    updated_at: new Date()
  });
}

export { createSession, validateSession, deleteSession, deleteUserSessions, refreshSession };
