const db = require('../db');
const { AppError } = require('../utils/helpers');

async function getAccessRole(userId, deviceId) {
  const [own] = await db.query(
    `SELECT 1 FROM device_ownership
     WHERE device_id = ? AND owner_id = ? AND ended_at IS NULL`,
    [deviceId, userId],
  );
  if (own[0]) return 'owner';

  const [share] = await db.query(
    'SELECT 1 FROM device_sharing WHERE device_id = ? AND viewer_id = ?',
    [deviceId, userId],
  );
  if (share[0]) return 'viewer';
  return null;
}

async function requireAccess(userId, deviceId) {
  const role = await getAccessRole(userId, deviceId);
  if (!role) throw new AppError(403, 'Access Denied');
  return role;
}

async function requireOwner(userId, deviceId) {
  const role = await requireAccess(userId, deviceId);
  if (role !== 'owner') throw new AppError(403, 'Only the owner can do this');
  return role;
}

async function writeAudit(action, userId, deviceId, detail) {
  await db.query(
    'INSERT INTO audit_log (action, user_id, device_id, detail) VALUES (?,?,?,?)',
    [action, userId, deviceId, detail || null],
  );
}

module.exports = { getAccessRole, requireAccess, requireOwner, writeAudit };
