using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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 RoleController:ApiControllerBase<RoleController>
    {
        public RoleController(ILogger<RoleController> logger,IServiceProvider service) : base(logger,service) {
        }

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

        /// <summary>
        /// 查询角色是否注册
        /// </summary>
        /// <param name="roleName">角色名称</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Roles),200)]
        public Roles GetRoles(string roleName) {
            var qu = this.Db.Roles.Where(m => m.Name == roleName);
            if(qu.Any()) {
                return qu.First();
            } else {
                throw new ApiException("没有找到该角色");
            }
        }

    }

}
