using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Services;

namespace PlotLine.Controllers;

[Authorize]
[Route("api/story-intelligence")]
public sealed class StoryIntelligenceVisualisationController(
    ICurrentUserService currentUser,
    IStoryIntelligenceVisualisationSnapshotService snapshots,
    ILogger<StoryIntelligenceVisualisationController> logger) : ControllerBase
{
    [HttpGet("runs/{runId:int}/visualisation-snapshot")]
    public async Task<IActionResult> GetSnapshot(int runId)
    {
        if (currentUser.UserId is not int userId)
        {
            return Unauthorized();
        }

        var snapshot = await snapshots.BuildSnapshotAsync(runId, userId);
        if (snapshot is not null)
        {
            var current = snapshot.Scenes.FirstOrDefault(scene => scene.IsCurrent) ?? snapshot.Scenes.LastOrDefault();
            logger.LogInformation(
                "Story Intelligence browser endpoint synchronisation: import session {ImportSessionId}; run {RunId}; current chapter {CurrentChapter}; current scene {CurrentScene}; scene result {SceneResultId}; snapshot version Endpoint; change token {ChangeToken}.",
                snapshot.ImportSessionId,
                snapshot.RunId,
                current?.ChapterLabel,
                current?.SceneNumber,
                snapshot.Diagnostics.SelectedCurrentSceneResultId,
                snapshot.ChangeToken);
        }
        return snapshot is null ? NotFound() : Ok(snapshot);
    }

    [HttpGet("import-sessions/{importSessionId:int}/visualisation-snapshot")]
    public async Task<IActionResult> GetImportSessionSnapshot(int importSessionId)
    {
        if (currentUser.UserId is not int userId)
        {
            return Unauthorized();
        }

        var snapshot = await snapshots.BuildImportSessionSnapshotAsync(importSessionId, userId);
        if (snapshot is not null)
        {
            var current = snapshot.Scenes.FirstOrDefault(scene => scene.IsCurrent) ?? snapshot.Scenes.LastOrDefault();
            logger.LogInformation(
                "Story Intelligence browser endpoint synchronisation: import session {ImportSessionId}; run {RunId}; current chapter {CurrentChapter}; current scene {CurrentScene}; scene result {SceneResultId}; snapshot version Endpoint; change token {ChangeToken}.",
                snapshot.ImportSessionId,
                snapshot.RunId,
                current?.ChapterLabel,
                current?.SceneNumber,
                snapshot.Diagnostics.SelectedCurrentSceneResultId,
                snapshot.ChangeToken);
        }
        return snapshot is null ? NotFound() : Ok(snapshot);
    }
}
