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

namespace JobTrackerApi.Controllers;

[ApiController]
[Route("api/ai/settings")]
[Authorize(AuthenticationSchemes = "local")]
public sealed class AiSettingsController(
    UserManager<ApplicationUser> users,
    AiPrivacyPolicy privacyPolicy) : ControllerBase
{
    public sealed record AiSettingsRequest(bool Enabled, bool ExternalProcessingAllowed);
    public sealed record AiSettingsDto(
        bool Enabled,
        bool ExternalProcessingAllowed,
        bool ExternalProcessingAvailable,
        bool EffectiveExternalProcessing,
        string Provider);

    [HttpGet]
    public async Task<ActionResult<AiSettingsDto>> Get(CancellationToken cancellationToken)
    {
        var user = await users.GetUserAsync(User);
        if (user is null) return Unauthorized();
        return Ok(await ToDtoAsync(user, cancellationToken));
    }

    [HttpPut]
    public async Task<ActionResult<AiSettingsDto>> Put(
        [FromBody] AiSettingsRequest request,
        CancellationToken cancellationToken)
    {
        var user = await users.GetUserAsync(User);
        if (user is null) return Unauthorized();

        user.AiEnabled = request.Enabled;
        user.ExternalAiProcessingAllowed = request.ExternalProcessingAllowed;
        var result = await users.UpdateAsync(user);
        if (!result.Succeeded)
            return Problem("AI privacy settings could not be saved.", statusCode: StatusCodes.Status500InternalServerError);

        return Ok(await ToDtoAsync(user, cancellationToken));
    }

    private async Task<AiSettingsDto> ToDtoAsync(ApplicationUser user, CancellationToken cancellationToken)
    {
        var decision = await privacyPolicy.EvaluateAsync(user.Id, cancellationToken);
        return new AiSettingsDto(
            user.AiEnabled,
            user.ExternalAiProcessingAllowed,
            privacyPolicy.ExternalProcessingAvailable,
            decision.ExternalProcessingAllowed,
            decision.Provider);
    }
}
