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/tenant/access/jobs")]
[Authorize(Policy = BackendPermissions.TenantJobManage)]
public sealed class BackgroundJobsController(
    IBackgroundJobQueue backgroundJobQueue,
    IBackgroundJobOperations backgroundJobOperations,
    ITenantContext tenantContext,
    ICurrentUser currentUser) : 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 backgroundJobOperations.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 backgroundJobQueue.EnqueueAsync(request.ToCommand(tenantId), cancellationToken));
    }

    [HttpGet("{jobId:guid}")]
    [EndpointSummary("查询租户后台任务详情")]
    public async Task<ActionResult<BackgroundJobItem>> Detail(Guid jobId, CancellationToken cancellationToken)
    {
        var item = await backgroundJobOperations.GetAsync(jobId, ResolveTenantId(), cancellationToken);
        return item is null ? NotFound() : Ok(item);
    }

    [HttpPost("{jobId:guid}/cancel")]
    [EndpointSummary("取消租户后台任务")]
    public async Task<ActionResult<BackgroundJobItem>> Cancel(
        Guid jobId,
        CancelBackgroundJobDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await backgroundJobOperations.RequestCancellationAsync(
            jobId, ResolveTenantId(), ResolveUserId(), request.Reason, cancellationToken));
    }

    [HttpPost("{jobId:guid}/retry")]
    [EndpointSummary("重试失败或已取消的租户后台任务")]
    public async Task<ActionResult<BackgroundJobItem>> Retry(Guid jobId, CancellationToken cancellationToken)
    {
        return Ok(await backgroundJobOperations.RetryAsync(
            jobId, ResolveTenantId(), ResolveUserId(), cancellationToken));
    }

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

    private Guid ResolveUserId()
    {
        return currentUser.UserId ?? throw new InvalidOperationException("Current user was not resolved.");
    }
}