const Permission = require('../../models/Permission');
const { logger } = require('../../middleware/logger');

class PermissionRepository {
  constructor(unitOfWork) {
    this.unitOfWork = unitOfWork;
  }

  async getAllPermissions() {
    logger.info('PermissionRepository.getAllPermissions:start');
    try {
      const conn = this.unitOfWork.connection;
      const [rows] = await conn.query(
        `SELECT id, name, description, is_active FROM permissions`
      );
      logger.info('PermissionRepository.getAllPermissions:success', { count: rows.length });
      return rows.map(row => new Permission(row));
    } catch (error) {
      logger.error('PermissionRepository.getAllPermissions:error', { error: error.message });
      throw error;
    }
  }

  async createPermission({ name, description, is_active, created_by }) {
    logger.info('PermissionRepository.createPermission:start', { name });
    try {
      const conn = this.unitOfWork.connection;
      const [result] = await conn.query(
        `INSERT INTO permissions (name, description, is_active, created_by) VALUES (?, ?, ?, ?)`,
        [name, description, is_active !== undefined ? is_active : true, created_by]
      );
      logger.info('PermissionRepository.createPermission:success', { id: result.insertId, name });
      return new Permission({
        id: result.insertId,
        name,
        description,
        is_active: is_active !== undefined ? is_active : true,
        created_by
      });
    } catch (error) {
      logger.error('PermissionRepository.createPermission:error', { name, error: error.message });
      throw error;
    }
  }

  async getPermissionsByUserId(userId) {
    logger.info('PermissionRepository.getPermissionsByUserId:start', { userId });
    try {
      const conn = this.unitOfWork.connection;
      const [rows] = await conn.query(
        `SELECT p.id, p.name, p.description, p.is_active
         FROM user_permissions up
         JOIN permissions p ON up.permission_id = p.id
         WHERE up.user_id = ? AND p.is_active = TRUE`,
        [userId]
      );
      logger.info('PermissionRepository.getPermissionsByUserId:success', { userId, count: rows.length });
      return rows;
    } catch (error) {
      logger.error('PermissionRepository.getPermissionsByUserId:error', { userId, error: error.message });
      throw error;
    }
  }
}

module.exports = PermissionRepository;
