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 OperationContentManagementController(
    IOperationContentManagementService service,
    DirectContentActorResolver actorResolver) : ControllerBase
{
    [HttpGet("operations/{kind}")]
    [Authorize(Policy = BackendPermissions.TenantSiteContentManage)]
    [Authorize(Policy = TikuPolicies.TenantAllDataScope)]
    [RequireSaasFeature(SaasFeatureCatalog.SiteContent)]
    [EndpointSummary("查询运营内容")]
    [ProducesResponseType<CatalogList<OperationContentItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CatalogList<OperationContentItem>>> GetOperationContent(
        string kind,
        [FromQuery] DirectContentQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetOperationContentAsync(actorResolver.Resolve(), kind, query.ToFilter(),
            cancellationToken));
    }

    [HttpPut("operations/{kind}")]
    [Authorize(Policy = BackendPermissions.TenantSiteContentManage)]
    [Authorize(Policy = TikuPolicies.TenantAllDataScope)]
    [RequireSaasFeature(SaasFeatureCatalog.SiteContent)]
    [EndpointSummary("新增或更新运营内容")]
    [ProducesResponseType<ContentManagementResult<OperationContentItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ContentManagementResult<OperationContentItem>>> UpsertOperationContent(
        string kind,
        DirectOperationContentDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpsertOperationContentAsync(actorResolver.Resolve(), kind, request.ToCommand(),
            cancellationToken));
    }
}
