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

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("租户端-分类管理")]
[Authorize(Policy = TikuPolicies.CurrentTenantMember)]
[Produces("application/json")]
[Route("api/tenant/taxonomy/nodes")]
public sealed class TaxonomyController(
    ITenantContext tenantContext,
    ITaxonomyService taxonomyService) : ControllerBase
{
    [HttpGet]
    [RequireSaasFeature(SaasFeatureCatalog.Practice)]
    [EndpointSummary("查询租户分类节点")]
    public Task<IReadOnlyCollection<TaxonomyNodeItem>> List(CancellationToken cancellationToken)
    {
        return taxonomyService.ListAsync(RequireTenantId(), cancellationToken);
    }

    [HttpPost]
    [RequireSaasFeature(SaasFeatureCatalog.PrivateQuestionBank)]
    [Authorize(Policy = BackendPermissions.TenantContentManage)]
    [EndpointSummary("创建租户分类节点")]
    public Task<TaxonomyNodeItem> Create(
        CreateTaxonomyNodeDto request,
        CancellationToken cancellationToken)
    {
        return taxonomyService.CreateAsync(RequireTenantId(), request.ToCommand(), cancellationToken);
    }

    private Guid RequireTenantId()
    {
        return tenantContext.TenantId ?? throw new InvalidOperationException("Tenant was not resolved.");
    }
}