using Eshop.Application.Auth;
using Microsoft.AspNetCore.Mvc;
using Eshop.Web.Models;

namespace Eshop.Web.Areas.Admin.Controllers;

public class UsersController : AdminBaseController
{
    private readonly IUserAdministrationService _userAdministrationService;

    public UsersController(IUserAdministrationService userAdministrationService)
    {
        _userAdministrationService = userAdministrationService;
    }

    public async Task<IActionResult> Index()
    {
        var users = await _userAdministrationService.GetAllUsersWithRolesAsync();
        return View(users.Select(ToViewModel));
    }

    public async Task<IActionResult> Details(string id)
    {
        var user = await _userAdministrationService.GetUserWithRolesAsync(id);
        if (user is null) return NotFound();

        return View(ToViewModel(user));
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> UpdateRoles(string id, List<string> selectedRoles)
    {
        var result = await _userAdministrationService.UpdateUserRolesAsync(id, selectedRoles);
        if (!result.Success)
        {
            TempData["ErrorMessage"] = string.Join(" ", result.Errors);
            return RedirectToAction(nameof(Details), new { id });
        }

        TempData["SuccessMessage"] = "Roles updated successfully.";
        return RedirectToAction(nameof(Details), new { id });
    }

    private static UserWithRolesViewModel ToViewModel(UserWithRolesDto dto) =>
        new()
        {
            User = dto.User,
            Roles = dto.Roles,
            AllRoles = dto.AllRoles,
        };
}
