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

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("租户端-后台任务")]
[Route("api/backoffice/tenant/jobs")]
[Authorize(Policy = BackendPermissions.TenantJobManage)]
public sealed class BackgroundJobsController(
    IBackgroundJobService backgroundJobService,
    ITenantContext tenantContext) : ControllerBase
{
    [HttpGet]
    [EndpointSummary("查询租户后台任务")]
    [ProducesResponseType<IReadOnlyCollection<BackgroundJobItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<IReadOnlyCollection<BackgroundJobItem>>> List(
        [FromQuery] string? jobType,
        [FromQuery] int? limit,
        CancellationToken cancellationToken)
    {
        var tenantId = ResolveTenantId();
        return Ok(await backgroundJobService.ListAsync(tenantId, jobType, limit ?? 50, cancellationToken));
    }

    [HttpPost]
    [EndpointSummary("创建租户后台任务")]
    [ProducesResponseType<BackgroundJobItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<BackgroundJobItem>> Create(
        CreateBackgroundJobDto request,
        CancellationToken cancellationToken)
    {
        var tenantId = ResolveTenantId();
        return Ok(await backgroundJobService.EnqueueAsync(request.ToCommand(tenantId), cancellationToken));
    }

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