using DigitalData.Core.API;
using DigitalData.Core.DTO;
using DigitalData.UserManager.Application.Contracts;
using DigitalData.UserManager.Application.DTOs.ModuleOfUser;
using DigitalData.UserManager.Domain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DigitalData.UserManager.API.Controllers
{
    [Authorize]
    public class ModuleOfUserController : CRUDControllerBaseWithErrorHandling<IModuleOfUserService, ModuleOfUserCreateDto, ModuleOfUserReadDto, ModuleOfUserUpdateDto, ModuleOfUser, int>
    {
        public ModuleOfUserController(ILogger<ModuleOfUserController> logger, IModuleOfUserService service) : base(logger, service)
        {
        }

        [NonAction]
        public override Task<IActionResult> GetAll() => base.GetAll();

        [HttpGet]
        public async Task<IActionResult> GetAll(string? username = null)
        {

            if (username is not null)
                return await _service.ReadByUserAsync(username).ThenAsync(Ok, IActionResult (m, n) =>
                {
                    _logger.LogNotice(n);
                    return StatusCode(StatusCodes.Status500InternalServerError);
                });

            return await base.GetAll();
        }

        [HttpDelete]
        public async Task<IActionResult> Delete([FromQuery] int moduleId, [FromQuery]int userId)
        {
            try
            {
                return await _service.DeleteAsyncByModuleUserId(moduleId, userId).ThenAsync(Ok, IActionResult (m, n) =>
                {
                    _logger.LogNotice(n);
                    return BadRequest();
                });
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, "{Message}", ex.Message);
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }
    }
}