using System;
using System.Linq;
using Falcon.Extend;
using FAuth.DataBase.Tables;
using FAuth.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace FAuth.Controllers.api
{
    /// <summary>
    /// 角色组控制器
    /// </summary>
    public class RoleGroupController:ApiControllerBase<RoleGroupController>
    {
        public RoleGroupController(ILogger<RoleGroupController> logger,IServiceProvider service) : base(logger,service) {
        }

        /// <summary>
        /// 添加新角色组
        /// </summary>
        /// <param name="name">角色组名称</param>
        /// <param name="description">角色组说明</param>
        /// <returns>角色组信息</returns>
        [HttpPost]
        [ProducesResponseType(typeof(RoleGroup),200)]
        public RoleGroup AddNewGroup(string name,string description) {
            if(name.IsNullOrEmpty()) {
                throw new ApiArgumentNullException(nameof(name));
            }
            var qu = this.Db.RoleGroups.Where(m => m.Name == name);
            if(qu.Any()) {
                throw new ApiException($"角色组{name}已经存在，不可以重复创建!");
            }
            var model = new RoleGroup {
                Name = name,
                Description = description,
            };
            this.Db.Entry(model).State = EntityState.Added;
            this.Db.SaveChangesAsync().Wait();
            return model;
        }

        /// <summary>
        /// 查询角色组是否注册
        /// </summary>
        /// <param name="name">角色组名称</param>
        /// <returns>角色组信息</returns>
        [HttpPost]
        [ProducesResponseType(typeof(RoleGroup),200)]
        public RoleGroup GetRoleGroups(string name) {
            if(string.IsNullOrEmpty(name))
                throw new ApiArgumentNullException(nameof(name));
            var qu = this.Db.RoleGroups.Where(m => m.Name == name);
            if(qu.Any()) {
                return qu.First();
            } else {
                throw new Exception("没有找到该角色");
            }
        }

    }

}
