import { pool } from '../db.js';

export async function createAuthSession({
  userId,
  refreshTokenHash,
  csrfTokenHash,
  userAgent,
  ipAddress,
  expiresAt,
}) {
  const sql = `
    INSERT INTO uno_bff.auth_sessions
    (
      user_id,
      refresh_token_hash,
      csrf_token_hash,
      status,
      user_agent,
      ip_address,
      expires_at,
      last_seen_at
    )
    VALUES
    (
      $1, $2, $3, 'active', $4, $5, $6, now()
    )
    RETURNING
      id,
      user_id,
      refresh_token_hash,
      csrf_token_hash,
      status,
      user_agent,
      ip_address,
      expires_at,
      last_seen_at,
      revoked_at,
      created_at,
      updated_at
  `;

  const params = [
    userId,
    refreshTokenHash,
    csrfTokenHash,
    userAgent || null,
    ipAddress || null,
    expiresAt,
  ];

  const { rows } = await pool.query(sql, params);
  return rows[0];
}

export async function revokeSession(sessionId) {
  const sql = `
    UPDATE uno_bff.auth_sessions
    SET
      status = 'revoked',
      revoked_at = now(),
      updated_at = now()
    WHERE id = $1
      AND status = 'active'
  `;

  await pool.query(sql, [sessionId]);
}

export async function getAuthSession(sessionId) {
  const sql = `
    SELECT id, user_id, refresh_token_hash, csrf_token_hash, status, expires_at
    FROM uno_bff.auth_sessions
    WHERE id = $1 AND status = 'active' AND expires_at > now()
  `;
  const result = await pool.query(sql, [sessionId]);
  return result.rows[0] || null;
}

export async function rotateSessionTokens(sessionId, newRefreshTokenHash, newCsrfTokenHash) {
  const sql = `
    UPDATE uno_bff.auth_sessions
    SET
      refresh_token_hash = $2,
      csrf_token_hash = $3,
      updated_at = now()
    WHERE id = $1 AND status = 'active'
    RETURNING id, user_id
  `;
  const result = await pool.query(sql, [sessionId, newRefreshTokenHash, newCsrfTokenHash]);
  return result.rows[0] || null;
}