using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tiku.Api.Contracts;
using Tiku.Application.Assets;
using Tiku.Application.Catalog;
using Tiku.Application.Security;

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("学生端-题目视频")]
[Authorize(Policy = TikuPolicies.CurrentTenantMember)]
[Tiku.Api.Security.RequireSaasFeature(SaasFeatureCatalog.Video)]
[Produces("application/json")]
[Route("api/questions/videos")]
public sealed class QuestionVideosController(
    IVideoPlaybackService videoPlaybackService,
    ICurrentUser currentUser,
    ITenantContext currentTenant) : ControllerBase
{
    [HttpGet]
    [EndpointSummary("查询单道题目的解析视频")]
    [ProducesResponseType<CatalogList<QuestionVideoCatalogItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CatalogList<QuestionVideoCatalogItem>>> List(
        [FromQuery] QuestionVideoQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await videoPlaybackService.GetQuestionVideosAsync(ResolveActor(), query.ToQuery(), cancellationToken));
    }

    [HttpPost("batch")]
    [EndpointSummary("批量查询题目解析视频")]
    [ProducesResponseType<CatalogList<QuestionVideoCatalogItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CatalogList<QuestionVideoCatalogItem>>> Batch(
        QuestionVideoQueryDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await videoPlaybackService.GetQuestionVideosAsync(ResolveActor(), request.ToQuery(), cancellationToken));
    }

    private VideoPlaybackActor ResolveActor()
    {
        if (currentTenant.TenantId is null || currentUser.UserId is null)
        {
            throw new VideoPlaybackException("Current video actor was not resolved.", "video_access_denied");
        }

        return new VideoPlaybackActor(currentTenant.TenantId.Value, currentUser.UserId.Value);
    }
}
