using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Filters;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Redis;
using Siger.Middlelayer.Redis.RedisEntities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Request;

namespace Siger.ApiConfig.Controller
{
    [NoTokenValidateFilter]
    [ApiController]
    [Route("config/[controller]/[action]")]
    [EnableCors("Cors")]
    public class DbNameConfigController : ControllerBase
    {
        private readonly ISigerProjectRepository _projectRepository;
        public DbNameConfigController(ISigerProjectRepository projectRepository)
        {
            _projectRepository = projectRepository;
        }

        [HttpGet]
        public IActionResult GetConfig(int projectId)
        {
            var project = _projectRepository.Get(q => q.id == projectId && q.status == (int) RowState.Valid);
            if (project == null)
            {
                throw new BadRequestException(RequestEnum.ProjectNotFound);
            }

            var license = RedisCache.Instance.GetDbName(project.companyid.ToInt(), project.id);
            return new ObjectResult(license);
        }

        [HttpPost]
        public IActionResult SetConfig([FromBody]RequestSetDbNameConfig request)
        {
            if (string.IsNullOrWhiteSpace(request.projectId))
            {
                throw new BadRequestException(RequestEnum.IdIsEmpty);
            }
            var project = _projectRepository.Get(q => q.id == request.projectId.ToInt() && q.status == (int)RowState.Valid);
            if (project == null)
            {
                throw new BadRequestException(RequestEnum.ProjectNotFound);
            }

            var entity = new DbNameConfig
            {
                Cid = project.companyid.ToInt(),
                Pid = project.id,
                CompanyName = project.title,
                MysqlDbName = $"{project.companyid}_{project.id}",
                RedisDbName = request.redisdb,
                HBaseDbName = $"{project.companyid}_{project.id}",
                SCService = request.scservice,
                SCPort = request.scport
            };
            RedisCache.Instance.AddDbNameConfig(entity);
            return new ObjectResult(CommonEnum.Succefull);
        }
    }
}