using ErsatzTV.Application.Movies;
using ErsatzTV.Core.Api;
using ErsatzTV.Core.Api.Media;
using ErsatzTV.Core.Api.Movies;
using ErsatzTV.Core.Domain;
using ErsatzTV.Extensions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace ErsatzTV.Controllers.Api;

[ApiController]
public class MoviesController(IMediator mediator) : ControllerBase
{
    [HttpGet("/api/v1/movies/{id:int}", Name = "GetMovieById")]
    [Tags("Movies")]
    [EndpointSummary("Get a movie by id")]
    [EndpointGroupName("general")]
    [ProducesResponseType(typeof(MovieDetailResponseModel), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetById(int id, CancellationToken cancellationToken)
    {
        Option<MovieViewModel> result = await mediator.Send(new GetMovieById(id), cancellationToken);
        return result.Map(vm => Project(id, vm)).ToGetResult();
    }

    private static MovieDetailResponseModel Project(int id, MovieViewModel vm) =>
        new(
            id,
            vm.Title,
            vm.Year,
            vm.Plot,
            vm.Genres,
            vm.Tags,
            vm.Studios,
            vm.ContentRatings,
            vm.Languages,
            vm.Actors.Map(a => new ActorResponseModel(a.Id, a.Name, a.Role, ApiArtwork.Root(a.Thumb, ArtworkKind.Thumbnail))).ToList(),
            vm.Directors,
            vm.Writers,
            vm.Path,
            vm.LocalPath,
            vm.MediaItemState,
            ApiArtwork.Root(vm.Poster, ArtworkKind.Poster),
            ApiArtwork.Root(vm.FanArt, ArtworkKind.FanArt));
}
