using Lada.Framework.Data.Domains.Identity;
using Lada.Framework.DTO;
using Lada.Framework.DTO.SmartTable;
using Lada.Framework.Infrastructures.Helpers;
using Ladaer.BackEnd.Infrastructures.DTO.Models.Itentity;
using Ladaer.BackEnd.Infrastructures.Services.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Ladaer.BackEnd.Controllers.Identity
{
    /// <summary>
    /// Controller để quản lý Permission Groups (tập hợp các Role)
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(Roles = "Founder")] // Sử dụng pattern mới: Controller.Action
    public class PermissionController : ControllerBase
    {
        private readonly IPermissionService _permissionService;

        public PermissionController(IPermissionService permissionService)
        {
            _permissionService = permissionService;
        }

        [HttpGet("GetPermissions")]
        [Authorize(Roles = "Permission.Search")]
        public async Task<IActionResult> GetPermissions()
        {
            var roles = await _permissionService.GetAllPermissionsAsync();
            return Ok(roles);
        }


        /// <summary>
        /// Xóa Permission Group
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize(Roles = "Permission.Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                var success = await _permissionService.DeletePermissionAsync(id);
                if (!success)
                {
                    return NotFound();
                }

                return Ok(new { Success = true, Message = "Permission đã được xóa thành công" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Success = false, ex.Message });
            }
        }

        /// <summary>
        /// Gán Permission cho User
        /// </summary>
        [HttpPost("Assign")]
        [Authorize(Roles = "Permission.AssignToUser")]
        public async Task<IActionResult> AssignToUser([FromBody] AssignPermissionRequest request)
        {
            try
            {
                var result = await _permissionService.AssignPermissionToUserAsync(request.UserId, request.PermissionId);
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new BaseResult { Result = Result.Failed, Message = ex.Message });
            }
        }

        /// <summary>
        /// Xóa Permission khỏi User
        /// </summary>
        [HttpPost("remove")]
        [Authorize(Roles = "Permission.RemoveFromUser")]
        public async Task<IActionResult> RemoveFromUser([FromBody] RemovePermissionRequest request)
        {
            try
            {
                var success = await _permissionService.RemovePermissionFromUserAsync(request.UserId);
                if (!success)
                {
                    return BadRequest(new { Success = false, Message = "Không thể xóa Permission khỏi User" });
                }

                return Ok(new { Success = true, Message = "Permission đã được xóa khỏi User thành công" });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Success = false, ex.Message });
            }
        }

        /// <summary>
        /// Lấy danh sách Role trong Permission
        /// </summary>
        [HttpGet("{id}/roles")]
        [Authorize(Roles = "Permission.GetRoles")]
        public async Task<IActionResult> GetRoles(int id)
        {
            var roles = await _permissionService.GetRolesInPermissionAsync(id);
            return Ok(roles);
        }

        /// <summary>
        /// Tìm kiếm Permission với phân trang
        /// </summary>
        [HttpPost("search")]
        [Authorize(Roles = "Permission.Search")]
        public async Task<IActionResult> Search([FromBody] SmartTableParam param)
        {
            var result = await _permissionService.SearchAsync(param);
            return Ok(result);
        }

        /// <summary>
        /// Lấy tất cả Roles có thể gán cho Permission
        /// </summary>
        [HttpGet("available-roles")]
        [Authorize(Roles = "Permission.GetAvailableRoles")]
        public async Task<IActionResult> GetAvailableRoles()
        {
            var roles = await _permissionService.GetAllAvailableRolesAsync();
            return Ok(roles);
        }

        /// <summary>
        /// Tạo hoặc cập nhật Permission (theo pattern AgencyController)
        /// </summary>
        [HttpPost("CreateOrUpdate")]
        [Authorize(Roles = "Permission.CreateOrUpdate")]
        public async Task<IActionResult> CreateOrUpdate([FromBody] PermissionModel permissionModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var currentUser = User.GetCurrentUser();
            permissionModel.UpdatedBy = currentUser.UserId;
            permissionModel.UpdatedByUserName = currentUser.UserName;

            if (permissionModel.UpdatedBy <= 0 || string.IsNullOrEmpty(permissionModel.UpdatedByUserName))
            {
                return BadRequest("Không xác định được người dùng");
            }

            var result = await _permissionService.CreateOrUpdate(permissionModel);
            return Ok(result);
        }

        /// <summary>
        /// Lấy thông tin Permission theo ID (trả về PermissionModel)
        /// </summary>
        [HttpGet("GetById")]
        [Authorize(Roles = "Permission.GetById")]
        public async Task<IActionResult> GetById(int id)
        {
            var result = await _permissionService.GetById(id);
            return Ok(result);
        }

        /// <summary>
        /// Cập nhật danh sách Role của Permission (hàm riêng biệt)
        /// </summary>
        [HttpPut("UpdateRoles")]
        [Authorize(Roles = "Permission.UpdateRoles")]
        public async Task<IActionResult> UpdatePermissionRoles([FromBody] PermissionRoleModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var currentUser = User.GetCurrentUser();
                model.CreatedBy = currentUser.UserId;
                model.CreatedByUserName = currentUser.UserName;
                var result = await _permissionService.UpdatePermissionRoles(model);
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { Success = false, ex.Message });
            }
        }
    }

    // DTOs for requests
    public class CreatePermissionRequest
    {
        public string Name { get; set; } = string.Empty;
        public string? Description { get; set; }
        public List<int> RoleIds { get; set; } = new List<int>();
    }

    public class UpdatePermissionRequest
    {
        /// <summary>
        /// PermissionId
        /// </summary>
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public string? Description { get; set; }

        /// <summary>
        /// Danh sách Role
        /// </summary>
        public List<int> RoleIds { get; set; } = new List<int>();
    }

    public class AssignPermissionRequest
    {
        public int UserId { get; set; }
        public int PermissionId { get; set; }
    }

    public class RemovePermissionRequest
    {
        public int UserId { get; set; }
    }

}
