using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Tiku.Api.Contracts;
using Tiku.Api.Security;
using Tiku.Application.Assets;
using Tiku.Application.Catalog;
using Tiku.Application.Content;
using Tiku.Application.Jobs;
using Tiku.Application.Security;
using Tiku.Domain.Catalog;
using Tiku.Domain.Content;

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("租户端-内容直接管理")]
[Produces("application/json")]
[Route("api/tenant/content")]
public sealed class VideoManagementController(
    IVideoManagementService service,
    DirectContentActorResolver actorResolver) : ControllerBase
{
    [HttpGet("videos")]
    [Authorize(Policy = BackendPermissions.TenantVideoManage)]
    [Authorize(Policy = TikuPolicies.TenantAllDataScope)]
    [RequireSaasFeature(SaasFeatureCatalog.Video)]
    [EndpointSummary("查询租户视频解析")]
    [ProducesResponseType<CatalogList<VideoManagementItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CatalogList<VideoManagementItem>>> GetVideos(
        [FromQuery] DirectContentQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetVideosAsync(actorResolver.Resolve(), query.ToFilter(), cancellationToken));
    }

    [HttpPut("videos")]
    [Authorize(Policy = BackendPermissions.TenantVideoManage)]
    [Authorize(Policy = TikuPolicies.TenantAllDataScope)]
    [RequireSaasFeature(SaasFeatureCatalog.Video)]
    [EndpointSummary("新增或更新视频解析")]
    [ProducesResponseType<ContentManagementResult<VideoManagementItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ContentManagementResult<VideoManagementItem>>> UpsertVideo(
        DirectVideoDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpsertVideoAsync(actorResolver.Resolve(), request.ToCommand(), cancellationToken));
    }

    [HttpPost("question-videos")]
    [Authorize(Policy = BackendPermissions.TenantVideoManage)]
    [Authorize(Policy = TikuPolicies.TenantAllDataScope)]
    [RequireSaasFeature(SaasFeatureCatalog.Video)]
    [EndpointSummary("绑定题目与解析视频")]
    [ProducesResponseType<ContentManagementResult<QuestionVideoManagementItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ContentManagementResult<QuestionVideoManagementItem>>> BindQuestionVideo(
        DirectQuestionVideoDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.BindQuestionVideoAsync(actorResolver.Resolve(), request.ToCommand(),
            cancellationToken));
    }
}
