using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App.DataSource;
using OpenAuth.App.SysDatabaseLink;
using OpenAuth.Repository.Domain;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>  
    /// 日 期： 2024-03-02
    /// 描 述： 数据源管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DataSourceController : ControllerBase
    {
        private readonly DataSourceApp _app;
        public DataSourceController(DataSourceApp app)
        {
            _app = app;
        }
        /// <summary>
        /// 分页获取列表数据
        /// </summary>
        /// <param name="keyword">筛选条件</param>
        /// <param name="page">当前页</param>
        /// <param name="limit">每页条数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<DataSource>>>> LoadDataBaseInfo(string keyword, int page = 1, int limit = 15)
        {
            return await _app.LoadDataSourceList(keyword, page, limit);
        }
        /// <summary>
        /// 获取数据源列名
        /// </summary>
        /// <param name="code">数据源编码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<string>>> GetDataColName(string code)
        {
            return await _app.GetDataColName(code);
        }
        /// <summary>
        /// 获取单个数据源
        /// </summary>
        /// <param name="code">数据源编码</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Repository.Domain.DataSource> GetEntityByCode(string code)
        {
            return await _app.GetEntityByCode(code);
        }
        /// <summary>
        /// 新增数据源
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> AddOrUpdateForm(string id, DataSource entity)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.SaveEntity(id, entity);

            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除数据源
        /// </summary>
        /// <param name="keyValue">主键</param>
        [HttpPost]
        public async Task<Response<bool>> DeleteEntity(string keyValue)
        {
            var result = new Response<bool>();
            try
            {
                result = await _app.DeleteEntity(keyValue);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }
            return result;
        }
    }
}
