using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using TarninaHub.Application.Abstractions; using TarninaHub.Application.Dtos; using TarninaHub.Application.Security; namespace TarninaHub.Controllers; [ApiController] [ApiVersion("1.0")] [Route("api/knowledge-items")] [Authorize] public class KnowledgeItemsController : ControllerBase { private readonly IKnowledgeItemService _knowledgeItems; public KnowledgeItemsController(IKnowledgeItemService knowledgeItems) { _knowledgeItems = knowledgeItems; } [HttpGet] public async Task>> List( [FromQuery] string? kind, [FromQuery] string? challengeId, [FromQuery] string? q, CancellationToken cancellationToken) { var items = await _knowledgeItems.ListAsync(kind, challengeId, q, !IsStaff(), cancellationToken); return Ok(items); } [HttpGet("{knowledgeItemId}")] public async Task> GetById( string knowledgeItemId, CancellationToken cancellationToken) { var item = await _knowledgeItems.GetAsync(knowledgeItemId, cancellationToken); return item is null ? NotFound() : Ok(item); } [HttpPost] [Authorize(Policy = Policies.OperatorOrAdmin)] public async Task> Create( KnowledgeItemRequest request, CancellationToken cancellationToken) { var created = await _knowledgeItems.CreateAsync(request, cancellationToken); return CreatedAtAction(nameof(GetById), new { knowledgeItemId = created.Id }, created); } [HttpPut("{knowledgeItemId}")] [Authorize(Policy = Policies.OperatorOrAdmin)] public async Task> Update( string knowledgeItemId, KnowledgeItemRequest request, CancellationToken cancellationToken) { var updated = await _knowledgeItems.UpdateAsync(knowledgeItemId, request, cancellationToken); return updated is null ? NotFound() : Ok(updated); } [HttpPost("{knowledgeItemId}/publish")] [Authorize(Policy = Policies.OperatorOrAdmin)] public async Task> Publish( string knowledgeItemId, CancellationToken cancellationToken) { var published = await _knowledgeItems.PublishAsync(knowledgeItemId, cancellationToken); return published is null ? NotFound() : Ok(published); } private bool IsStaff() => User.IsInRole(RoleNames.Operator) || User.IsInRole(RoleNames.Manager) || User.IsInRole(RoleNames.Admin); }