const { getDB } = require('../config/database');

const ok = (res, data, message = 'Berhasil') => res.json({ success: true, message, data });
const err = (res, message = 'Terjadi kesalahan', code = 400) => res.status(code).json({ success: false, message });

async function logActivity(level, msg, userId = null, ip = null) {
  try {
    const db = getDB();
    await db.query('INSERT INTO logs (`level`, msg, user_id, ip) VALUES (?, ?, ?, ?)', [level, msg, userId, ip]);
  } catch (error) {
    console.error('Failed to log activity:', error);
  }
}

async function paginate(query, params, page = 1, limit = 10) {
  const db = getDB();
  const offset = (page - 1) * limit;
  // Wrapping sebagai subquery — lebih robust daripada regex replace
  const baseQuery = query.split(/ORDER BY/i)[0].split(/LIMIT/i)[0];
  const countQuery = `SELECT COUNT(*) as total FROM (${baseQuery}) as _count_sub`;
  const [countRows] = await db.query(countQuery, params);
  const total = countRows[0]?.total || 0;
  const [data] = await db.query(`${query} LIMIT ? OFFSET ?`, [...params, Number(limit), Number(offset)]);
  return { data, total, page: Number(page), limit: Number(limit), pages: Math.ceil(total / limit) };
}

function sanitize(str) {
  if (typeof str !== 'string') return str;
  return str.replace(/[<>"'&]/g, c => ({
    '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '&': '&amp;'
  })[c]);
}

module.exports = { ok, err, logActivity, paginate, sanitize };
