// ***********************************************************************
// 
//     AgileWebs
// 
// ***********************************************************************
using Asp.Versioning;
using Core.Thalos.BuildingBlocks;
using Core.Thalos.Provider.Contracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StatusEnum = Core.Blueprint.Mongo.StatusEnum;
using UserRequest = Core.Thalos.Domain.Contexts.Onboarding.Request.UserRequest;
namespace LSA.Core.Thalos.API.Controllers
{
    /// 
    /// Handles all requests for user authentication.
    /// 
    [ApiVersion("1.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [Produces(MimeTypes.ApplicationJson)]
    [Consumes(MimeTypes.ApplicationJson)]
    [ApiController]
    public class UserController(IUserProvider service) : ControllerBase
    {
        /// 
        /// Gets all users.
        /// 
        /// A token to cancel the asynchronous operation.
        /// The  found entity.
        [HttpGet]
        [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
        [Permission("UserManagement.Read")]
        public async Task GetAllUsers(CancellationToken cancellationToken)
        {
            var result = await service.GetAllUsers(cancellationToken).ConfigureAwait(false);
            return Ok(result);
        }
        /// 
        /// Gets the user by mongo identifier.
        /// 
        /// The user Mongo identifier.
        /// A token to cancel the asynchronous operation.
        /// The  found entity.
        [HttpGet]
        [Route(Routes.Id)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
        [Permission("UserManagement.Read")]
        public async Task GetUserById([FromRoute] string _id, CancellationToken cancellationToken)
        {
            var result = await service.GetUserById(_id, cancellationToken).ConfigureAwait(false);
            return result == null ? NotFound("User not found") : Ok(result);
        }
        /// 
        /// Gets the user by email.
        /// 
        /// The user's email.
        /// A token to cancel the asynchronous operation.
        /// The  found entity.
        [HttpGet]
        [Route(Routes.Email)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.GoogleScheme}")]
        public async Task GetUserByEmail([FromRoute] string email, CancellationToken cancellationToken)
        {
            var result = await service.GetUserByEmail(email, cancellationToken).ConfigureAwait(false);
            return result == null ? NotFound("User not found") : Ok(result);
        }
        /// 
        /// Validates if a user exists on the database.
        /// 
        /// The user's email.
        /// A token to cancel the asynchronous operation.
        /// The  indicating existence.
        [HttpGet]
        [Route("{email}/ValidateExistence")]
        [ProducesResponseType(typeof(UserExistenceAdapter), StatusCodes.Status200OK)]
        [AllowAnonymous]
        public async Task ValidateUserExistence([FromRoute] string email, CancellationToken cancellationToken)
        {
            var result = await service.ValidateUserExistence(email, cancellationToken).ConfigureAwait(false);
            return result == null ? NotFound("User not found") : Ok(result);
        }
        /// 
        /// Creates a new user.
        /// 
        /// The user to be added.
        /// A token to cancel the asynchronous operation.
        /// The  created entity.
        [HttpPost(Routes.Register)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status201Created)]
        [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
        [Permission("UserManagement.Write")]
        public async Task CreateUserAsync([FromBody] UserRequest newUser, CancellationToken cancellationToken)
        {
            var result = await service.CreateUser(newUser, cancellationToken).ConfigureAwait(false);
            return Created("CreatedWithIdAsync", result);
        }
        /// 
        /// Updates a full user by mongo identifier.
        /// 
        /// The user Mongo identifier.
        /// The user to update.
        /// A token to cancel the asynchronous operation.
        /// The  updated entity.
        [HttpPut]
        [Route(Routes.Id)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
        [Permission("UserManagement.Write")]
        public async Task UpdateUserAsync([FromRoute] string _id, [FromBody] UserAdapter entity, CancellationToken cancellationToken)
        {
            if (_id != entity._Id)
                return BadRequest("User ID mismatch");
            var result = await service.UpdateUser(entity, cancellationToken).ConfigureAwait(false);
            return Ok(result);
        }
        /// 
        /// Logs in the user.
        /// 
        /// The user's email.
        /// A token to cancel the asynchronous operation.
        /// The  found entity.
        [HttpPatch(Routes.LogIn)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.GoogleScheme}")]
        public async Task LoginUserAsync([FromRoute] string email, CancellationToken cancellationToken)
        {
            var result = await service.LogInUser(email, cancellationToken).ConfigureAwait(false);
            return result == null ? NotFound($"The user with email: '{email}' was not found") : Ok(result);
        }
        /// 
        /// Logs out the user.
        /// 
        /// The user's email.
        /// A token to cancel the asynchronous operation.
        /// The  updated entity.
        [HttpPatch(Routes.LogOut)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.GoogleScheme}")]
        public async Task LogOutUserSessionAsync([FromRoute] string email, CancellationToken cancellationToken)
        {
            var result = await service.LogOutUserSession(email, cancellationToken).ConfigureAwait(false);
            return Ok(result);
        }
        /// 
        /// Changes the status of the user.
        /// 
        /// The user Mongo identifier.
        /// The new status of the user.
        /// A token to cancel the asynchronous operation.
        /// The  updated entity.
        [HttpPatch]
        [Route(Routes.ChangeStatus)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
        [Permission("UserManagement.Write")]
        public async Task ChangeUserStatus([FromRoute] string _id, [FromRoute] StatusEnum newStatus, CancellationToken cancellationToken)
        {
            var result = await service.ChangeUserStatus(_id, newStatus, cancellationToken).ConfigureAwait(false);
            if (result == null)
                return NotFound("User not found");
            return Ok(result);
        }
        /// 
        /// Gets a token for the user, including roles, permissions, and modules.
        /// 
        /// The user's email.
        /// A token to cancel the asynchronous operation.
        /// The  with user details.
        [HttpGet]
        [Route("{email}/GetTokenAdapter")]
        [ProducesResponseType(typeof(TokenAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = $"{Schemes.DefaultScheme}, {Schemes.GoogleScheme}")]
        public async Task GetTokenAdapter([FromRoute] string email, CancellationToken cancellationToken)
        {
            var tokenAdapter = await service.GetToken(email, cancellationToken).ConfigureAwait(false);
            return tokenAdapter == null ? NotFound($"User with email: {email} not found") : Ok(tokenAdapter);
        }
        /// 
        /// Deletes a user by mongo identifier.
        /// 
        /// The user Mongo identifier.
        /// A token to cancel the asynchronous operation.
        /// The deleted  entity.
        /// The user deleted.
        /// The user not found.
        [HttpDelete]
        [Route(Routes.Id)]
        [ProducesResponseType(typeof(UserAdapter), StatusCodes.Status200OK)]
        [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)]
        [Permission("UserManagement.Write")]
        public async Task DeleteUserAsync([FromRoute] string _id, CancellationToken cancellationToken)
        {
            var result = await service.DeleteUser(_id, cancellationToken).ConfigureAwait(false);
            return result == null ? NotFound("User not found") : Ok(result);
        }
    }
}