import { query, findOne, updateById, count } from '@zen/core/database';

const MAX_PAGE_LIMIT = 100;
const ALLOWED_SORT_COLUMNS = ['id', 'email', 'name', 'role', 'email_verified', 'created_at'];

async function getUserById(id) {
  return findOne('zen_auth_users', { id });
}

async function getUserByEmail(email) {
  return findOne('zen_auth_users', { email });
}

async function countUsers() {
  return count('zen_auth_users');
}

async function listUsers({ page = 1, limit = 10, sortBy = 'created_at', sortOrder = 'desc' } = {}) {
  const safePage = Math.max(1, page);
  const safeLimit = Math.min(Math.max(1, limit), MAX_PAGE_LIMIT);
  const offset = (safePage - 1) * safeLimit;
  const sortColumn = ALLOWED_SORT_COLUMNS.includes(sortBy) ? sortBy : 'created_at';
  const order = sortOrder.toLowerCase() === 'asc' ? 'ASC' : 'DESC';

  const result = await query(
    `SELECT id, email, name, role, image, email_verified, created_at FROM zen_auth_users ORDER BY "${sortColumn}" ${order} LIMIT $1 OFFSET $2`,
    [safeLimit, offset]
  );
  const total = await countUsers();

  return {
    users: result.rows,
    pagination: { page: safePage, limit: safeLimit, total, totalPages: Math.ceil(total / safeLimit) }
  };
}

async function updateUserById(id, fields) {
  const allowed = ['name', 'role', 'email_verified', 'image', 'language', 'updated_at'];
  const data = { updated_at: new Date() };
  for (const key of allowed) {
    if (fields[key] !== undefined) data[key] = fields[key];
  }
  return updateById('zen_auth_users', id, data);
}

export { getUserById, getUserByEmail, countUsers, listUsers, updateUserById };
