// ***********************************************************************
// 
//     Heath
// 
// ***********************************************************************
using Asp.Versioning;
using Core.Cerberos.Adapters;
using Core.Cerberos.Adapters.Attributes;
using Core.Cerberos.Adapters.Common.Constants;
using Core.Cerberos.Adapters.Common.Enums;
using Core.Cerberos.Domain.Contexts.Onboarding.Request;
using Core.Cerberos.Provider.Contracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace LSA.Core.Kerberos.API.Controllers
{
    /// 
    /// Handles all requests for permission authentication.
    /// 
    [ApiVersion(MimeTypes.ApplicationVersion)]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [Produces(MimeTypes.ApplicationJson)]
    [Consumes(MimeTypes.ApplicationJson)]
    [ApiController]
    public class PermissionController(IPermissionService service, ILogger logger) : ControllerBase
    {
        /// 
        /// Gets all the permissions.
        /// 
        /// The  found entities.
        /// The roles found.
        /// The roles not found error.
        /// The service internal error.
        [HttpGet]
        [Consumes(MimeTypes.ApplicationJson)]
        [Produces(MimeTypes.ApplicationJson)]
        [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.HeathScheme)]
        [Permission("PermissionManagement.Read, RoleManagement.Read")]
        public async Task GetAllPermissionsAsync()
        {
            try
            {
                var result = await service.GetAllPermissionsService();
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error in GetAllPermissionsAsync");
                return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
            }
        }
        /// 
        /// Gets all the permissions by permission identifiers.
        /// 
        /// The list of permission identifiers.
        /// The  found entities.
        /// The permissions found.
        /// The permissions not found error.
        /// The service internal error.
        [HttpPost]
        [Route(Routes.GetPermissionList)]
        [Consumes(MimeTypes.ApplicationJson)]
        [Produces(MimeTypes.ApplicationJson)]
        [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.HeathScheme)]
        [Permission("PermissionManagement.Read")]
        public async Task GetAllPermissionsByList([FromBody] string[] permissions)
        {
            if (permissions == null || !permissions.Any())
            {
                return BadRequest("Permission identifiers are required.");
            }
            try
            {
                var result = await service.GetAllPermissionsByListService(permissions);
                if (result == null || !result.Any())
                {
                    return NotFound("No permissions found for the given identifiers.");
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error in GetAllPermissionsByList");
                return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
            }
        }
        /// 
        /// Gets the permission by identifier.
        /// 
        /// The permission identifier.
        /// The  found entity.
        /// The permission found.
        /// The permission not found error.
        /// The service internal error.
        [HttpGet]
        [Route(Routes.Id)]
        [Consumes(MimeTypes.ApplicationJson)]
        [Produces(MimeTypes.ApplicationJson)]
        [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.HeathScheme)]
        [Permission("PermissionManagement.Read")]
        public async Task GetPermissionByIdAsync([FromRoute] string id)
        {
            try
            {
                var result = await service.GetPermissionByIdService(id);
                if (result is null) return NotFound($"permission with id: '{id}' not found");
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error in GetPermissionByIdAsync");
                return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
            }
        }
        /// 
        /// Creates a new permission.
        /// 
        /// The permission to be added.
        /// The  created entity.
        /// The permission created.
        /// The permission could not be created.
        /// The service internal e|ror.
        [HttpPost]
        [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status201Created)]
        [Authorize(AuthenticationSchemes = Schemes.HeathScheme)]
        [Permission("PermissionManagement.Write")]
        public async Task CreatePermissionAsync([FromBody] PermissionRequest newPermission)
        {
            try
            {
                var result = await service.CreatePermissionService(newPermission).ConfigureAwait(false);
                return Created("CreatedWithIdService", result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error in CreatePermissionAsync");
                return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
            }
        }
        /// 
        /// Updates a full permission by identifier.
        /// 
        /// The permission to update.
        /// The permission identifier.
        /// The  updated entity.
        /// The permission updated.
        /// The permission not found.
        /// The permission could not be updated.
        /// The service internal error.
        [HttpPut]
        [Route(Routes.Id)]
        [Consumes(MimeTypes.ApplicationJson)]
        [Produces(MimeTypes.ApplicationJson)]
        [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.HeathScheme)]
        [Permission("PermissionManagement.Write")]
        public async Task UpdatePermissionAsync(PermissionAdapter entity, string id)
        {
            try
            {
                var result = await service.UpdatePermissionService(entity, id);
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error in UpdatePermissionAsync");
                return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
            }
        }
        /// 
        /// Changes the status of the permission.
        /// 
        /// The permission identifier.
        /// The new status of the permission.
        /// The  updated entity.
        /// The permission updates.
        /// The permission not found.
        /// The permission could not be deleted.
        /// The service internal error.
        [HttpPatch]
        [Route(Routes.ChangeStatus)]
        [Consumes(MimeTypes.ApplicationJson)]
        [Produces(MimeTypes.ApplicationJson)]
        [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.HeathScheme)]
        [Permission("PermissionManagement.Write")]
        public async Task ChangePermissionStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus)
        {
            try
            {
                var result = await service.ChangePermissionStatusService(id, newStatus);
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error in ChangePermissionStatus");
                return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}");
            }
        }
    }
}