using JobTrackerApi.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace JobTrackerApi.Controllers;

[ApiController]
[Route("api/notification-settings")]
[Authorize(AuthenticationSchemes = "local")]
public sealed class NotificationSettingsController(UserManager<ApplicationUser> users) : ControllerBase
{
    public sealed record NotificationSettingsDto(bool EmailFollowUpRemindersEnabled);
    public sealed record SaveNotificationSettingsRequest(bool EmailFollowUpRemindersEnabled);

    [HttpGet]
    public async Task<ActionResult<NotificationSettingsDto>> Get()
    {
        var user = await users.GetUserAsync(User);
        return user is null ? Unauthorized() : Ok(new NotificationSettingsDto(user.EmailFollowUpRemindersEnabled));
    }

    [HttpPut]
    public async Task<ActionResult<NotificationSettingsDto>> Put([FromBody] SaveNotificationSettingsRequest request)
    {
        var user = await users.GetUserAsync(User);
        if (user is null) return Unauthorized();
        user.EmailFollowUpRemindersEnabled = request.EmailFollowUpRemindersEnabled;
        var result = await users.UpdateAsync(user);
        if (!result.Succeeded)
            return Problem("Notification settings could not be saved.", statusCode: StatusCodes.Status500InternalServerError);
        return Ok(new NotificationSettingsDto(user.EmailFollowUpRemindersEnabled));
    }
}
