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 QuestionManagementController(
    IQuestionManagementService service,
    DirectContentActorResolver actorResolver) : ControllerBase
{
    [HttpPost("questions")]
    [Authorize(Policy = BackendPermissions.TenantContentManage)]
    [Authorize(Policy = TikuPolicies.TenantAllDataScope)]
    [RequireSaasFeature(SaasFeatureCatalog.PrivateQuestionBank)]
    [EndpointSummary("创建题目及首个版本")]
    [ProducesResponseType<ContentManagementResult<QuestionManagementItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ContentManagementResult<QuestionManagementItem>>> CreateQuestion(
        DirectQuestionWriteDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.CreateQuestionAsync(actorResolver.Resolve(), request.ToCommand(true),
            cancellationToken));
    }

    [HttpPatch("questions")]
    [Authorize(Policy = BackendPermissions.TenantContentManage)]
    [Authorize(Policy = TikuPolicies.TenantAllDataScope)]
    [RequireSaasFeature(SaasFeatureCatalog.PrivateQuestionBank)]
    [EndpointSummary("更新题目并可选择创建新版本")]
    [ProducesResponseType<ContentManagementResult<QuestionManagementItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ContentManagementResult<QuestionManagementItem>>> UpdateQuestion(
        DirectQuestionWriteDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpdateQuestionAsync(actorResolver.Resolve(), request.ToCommand(false),
            cancellationToken));
    }
}
