using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;

namespace Siger.ApiConfig.Controller
{
    public class UserRolePowerController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerUserRolePowerRepository _rolePowerRepository;

        public UserRolePowerController(IUnitOfWork unitOfWork, ISigerUserRolePowerRepository rolePowerRepository)
        {
            _unitOfWork = unitOfWork;
            _rolePowerRepository = rolePowerRepository;
        }

        [HttpPost]
        public IActionResult SettingRolePowers(int roleid, int[] powerids)
        {
            var powers = _rolePowerRepository.GetList(q => q.roleid == roleid);
            foreach (var sigerUserRolePower in powers)
            {
                _rolePowerRepository.Delete(sigerUserRolePower);
            }

            if (powerids != null)
            {
                foreach (var powerid in powerids)
                {
                    var power = new siger_user_role_power();
                    power.roleid = roleid;
                    power.powerid = powerid;
                    _rolePowerRepository.Insert(power);
                }
            }

            if (_unitOfWork.Commit() > 0)
            {
                return Ok();
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }
    }
}