using Ladaer.BackEnd.Infrastructures.Services.Cms;
using Ladaer.BackEnd.Infrastructures.DTO.Models.Cms;
using Ladaer.BackEnd.Infrastructures.DTO.Items.Cms;
using Lada.Framework.DTO.SmartTable;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Lada.Framework.Infrastructures.Helpers;
using Microsoft.AspNetCore.Authorization;
using Ladaer.BackEnd.Infrastructures.DTO.Results.Cms;

namespace Ladaer.BackEnd.Controllers.Cms
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class ScriptConfigController : ControllerBase
    {
        private readonly IScriptConfigService _service;
        public ScriptConfigController(IScriptConfigService service)
        {
            _service = service;
        }

        /// <summary>
        /// Tìm kiếm cấu hình script
        /// </summary>
        [HttpPost("Search")]
        [Authorize(Roles = "ScriptConfig.Search")]
        public async Task<IActionResult> Search([FromBody] SmartTableParam param)
        {
            var result = await _service.Search(param);
            return Ok(result);
        }

        /// <summary>
        /// Lấy thông tin cấu hình script theo Id
        /// </summary>
        [HttpGet("GetById")]
        [Authorize(Roles = "ScriptConfig.GetById")]
        public async Task<IActionResult> GetById(int id)
        {
            var entity = await _service.GetByIdAsync(id);
            if (entity == null) return NotFound();
            return Ok(entity);
        }

        /// <summary>
        /// Thêm hoặc cập nhật cấu hình script
        /// </summary>
        [HttpPost("CreateOrUpdate")]

        [Authorize(Roles = "ScriptConfig.CreateOrUpdate")]
        public async Task<IActionResult> CreateOrUpdate([FromBody] ScriptConfigModel model)
        {
            var result = new ScriptConfigResult();
            var currentUser = User.GetCurrentUser();
            model.UpdatedBy = currentUser.UserId;
            model.UpdatedByUserName = currentUser.UserName;
            if (model.UpdatedBy <= 0 || string.IsNullOrEmpty(model.UpdatedByUserName))
            {
                return Ok(new { success = false, message = $"Không xác định được người dùng {currentUser.UserId} - {currentUser.UserName}" });
            }
            result = await _service.CreateOrUpdate(model);
            return Ok(result);
        }

        /// <summary>
        /// Xóa cấu hình script
        /// </summary>
        [HttpDelete("Delete")]
        [Authorize(Roles = "ScriptConfig.Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            await _service.DeleteAsync(id);
            return Ok(new { success = true });
        }
    }
}