using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using DigitalData.UserManager.Application.DTOs.Auth;
using DigitalData.UserManager.Application.Contracts;
using Microsoft.Extensions.Localization;
using DigitalData.UserManager.Application;
using System.Security.Claims;
using DigitalData.Core.Abstraction.Application.DTO;

namespace DigitalData.UserManager.API.Controllers;

[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
    private readonly ILogger<UserController> _logger;
    [Obsolete("Use MediatR")]
    private readonly IUserService _userService;
    private readonly IStringLocalizer<Resource> _localizer;

    [Obsolete("Use MediatR")]
    public AuthController(ILogger<UserController> logger, IUserService userService, IStringLocalizer<Resource> localizer)
    {
        _logger = logger;
        _userService = userService;
        _localizer = localizer;
    }

    [Authorize]
    [HttpGet("check")]
    public IActionResult CheckAuthentication() => Ok();

    [AllowAnonymous]
    [HttpPost("login")]
    public Task<IActionResult> Login([FromBody] LogInDto login) => throw new NotImplementedException();

    [Authorize]
    [HttpGet("user")]
    [Obsolete("Use MediatR")]
    public async Task<IActionResult> GetUserWithClaims()
    {
        try
        {
            // Extract the username from the Name claim.
            string? username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

            if (string.IsNullOrEmpty(username))
                return Unauthorized();

            return await _userService.ReadByUsernameAsync(username)
                .ThenAsync(Ok, IActionResult (m, n) =>
                {
                    _logger.LogNotice(n);
                    return NotFound(Result.Fail().Message(_localizer[Key.UserNotFound]));
                });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "{Message}", ex.Message);
            return StatusCode(StatusCodes.Status500InternalServerError);
        }
    }

    [Authorize]
    [HttpPost("logout")]
    public IActionResult Logout()
    {
        Response.Cookies.Delete("AuthToken", new()
        {
            Path = "/"
        });

        return Ok();
    }
}