using API.Contracts.Auth;
using API.Models;
using API.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace API.Controllers.Auth
{
    [ApiController]
    [Authorize(Policy = PolicyNames.AdminOnly)]
    [Route("auth/user")]
    public class AppUserController(UserManager<AppUser> userManager) : ControllerBase
    {
        [HttpGet]
        public async Task<ActionResult<IReadOnlyList<CurrentUserResponse>>> GetAppUsers()
        {
            var users = await userManager.Users
                .OrderBy(x => x.UserName)
                .ToListAsync();

            var tasks = users.Select(user => user.ToCurrentUserResponseAsync(userManager));
            return Ok(await Task.WhenAll(tasks));
        }

        [HttpGet("{id:guid}")]
        public async Task<ActionResult<CurrentUserResponse>> GetAppUserById([FromRoute] Guid id)
        {
            var user = await userManager.Users.FirstOrDefaultAsync(x => x.Id == id);
            if (user is null)
            {
                return NotFound(new { message = "Benutzer wurde nicht gefunden." });
            }

            return Ok(await user.ToCurrentUserResponseAsync(userManager));
        }
    }
}
