using Ladaer.BackEnd.Infrastructures.Services.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Ladaer.BackEnd.Controllers.Identity
{
    /// <summary>
    /// Controller để quản lý migration từ old role system sang new Permission system
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(Roles = "Founder")] // Chỉ Founder mới có quyền chạy migration
    public class RoleMigrationController : ControllerBase
    {
        private readonly IRoleMigrationService _migrationService;

        public RoleMigrationController(IRoleMigrationService migrationService)
        {
            _migrationService = migrationService;
        }

        /// <summary>
        /// Kiểm tra trạng thái migration
        /// </summary>
        [HttpGet("status")]
        [Authorize(Roles = "RoleMigration.GetMigrationStatus")]
        public async Task<IActionResult> GetMigrationStatus()
        {
            var isCompleted = await _migrationService.IsMigrationCompletedAsync();
            return Ok(new { IsCompleted = isCompleted });
        }

        /// <summary>
        /// Lấy danh sách Role mới sẽ được tạo
        /// </summary>
        [HttpGet("preview-roles")]
        public IActionResult PreviewNewRoles()
        {
            var roles = _migrationService.GetNewRolesToCreate();
            return Ok(roles);
        }

        /// <summary>
        /// Lấy mapping từ old roles sang Permission Groups
        /// </summary>
        [HttpGet("preview-mapping")]
        public IActionResult PreviewRoleMapping()
        {
            var mapping = _migrationService.GetOldRoleToPermissionMapping();
            return Ok(mapping);
        }

        /// <summary>
        /// Tạo các Role mới
        /// </summary>
        [HttpPost("create-roles")]
        [Authorize(Roles = "RoleMigration.CreateNewRoles")]
        public async Task<IActionResult> CreateNewRoles()
        {
            try
            {
                var createdRoles = await _migrationService.CreateNewRolesAsync();
                return Ok(new
                {
                    Success = true,
                    Message = $"Đã tạo {createdRoles.Count} roles mới",
                    CreatedRoles = createdRoles
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Success = false, ex.Message });
            }
        }

        /// <summary>
        /// Tạo Permission Groups mặc định
        /// </summary>
        [HttpPost("create-permissions")]
        [Authorize(Roles = "RoleMigration.CreateDefaultPermissions")]
        public async Task<IActionResult> CreateDefaultPermissions()
        {
            try
            {
                var createdPermissions = await _migrationService.CreateDefaultPermissionGroupsAsync();
                return Ok(new
                {
                    Success = true,
                    Message = $"Đã tạo {createdPermissions.Count} Permission Groups",
                    CreatedPermissions = createdPermissions
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Success = false, ex.Message });
            }
        }

        /// <summary>
        /// Migration Users từ old roles sang Permission Groups
        /// </summary>
        [HttpPost("migrate-users")]
        [Authorize(Roles = "RoleMigration.MigrateUsers")]
        public async Task<IActionResult> MigrateUsers()
        {
            try
            {
                var migratedCount = await _migrationService.MigrateUsersToPermissionGroupsAsync();
                return Ok(new
                {
                    Success = true,
                    Message = $"Đã migration {migratedCount} users",
                    MigratedUsers = migratedCount
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { Success = false, ex.Message });
            }
        }

        /// <summary>
        /// Chạy full migration process
        /// </summary>
        [HttpPost("run-full-migration")]
        [Authorize(Roles = "RoleMigration.RunFullMigration")]
        public async Task<IActionResult> RunFullMigration()
        {
            try
            {
                var result = await _migrationService.RunFullMigrationAsync();

                if (result.Success)
                {
                    return Ok(new
                    {
                        Success = true,
                        result.Message,
                        result.CreatedRoles,
                        result.CreatedPermissions,
                        result.MigratedUsers
                    });
                }
                else
                {
                    return BadRequest(new
                    {
                        Success = false,
                        result.Message,
                        result.Errors
                    });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(new { Success = false, ex.Message });
            }
        }
    }
}
