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

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("租户端-CRM")]
[Authorize(Policy = BackendPermissions.TenantCrmManage)]
[RequireSaasFeature(SaasFeatureCatalog.Crm)]
[Produces("application/json")]
[Route("api/tenant/crm")]
public sealed class CrmController(
    ICrmService crmService,
    ICurrentUser currentUser,
    ITenantContext currentTenant) : ControllerBase
{
    [HttpGet("config")]
    [EndpointSummary("查询 CRM 推送配置")]
    [ProducesResponseType<CrmConfigItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CrmConfigItem>> Config(CancellationToken cancellationToken)
    {
        return Ok(await crmService.GetConfigAsync(ResolveActor(), cancellationToken));
    }

    [HttpPut("config")]
    [EndpointSummary("保存 CRM 推送配置")]
    [ProducesResponseType<CrmConfigItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CrmConfigItem>> UpsertConfig(
        UpsertCrmConfigDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await crmService.UpsertConfigAsync(ResolveActor(), request.ToCommand(), cancellationToken));
    }

    [HttpGet("queue")]
    [EndpointSummary("查询 CRM webhook 队列")]
    [ProducesResponseType<CrmList<CrmQueueItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CrmList<CrmQueueItem>>> Queue(
        [FromQuery] CrmQueueQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await crmService.GetQueueAsync(ResolveActor(), query.ToQuery(), cancellationToken));
    }

    [HttpGet("dead-letters")]
    [EndpointSummary("查询 CRM 死信任务与汇总")]
    [ProducesResponseType<CrmDeadLetterResult>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CrmDeadLetterResult>> DeadLetters(
        [FromQuery] CrmQueueQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await crmService.GetDeadLettersAsync(ResolveActor(), query.ToQuery(), cancellationToken));
    }

    [HttpGet("queue/logs")]
    [EndpointSummary("查询 CRM 队列执行日志")]
    [ProducesResponseType<CrmList<CrmQueueLogItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CrmList<CrmQueueLogItem>>> Logs(
        [FromQuery] CrmQueueLogQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await crmService.GetLogsAsync(ResolveActor(), query.ToQuery(), cancellationToken));
    }

    [HttpPost("queue/action")]
    [EndpointSummary("重试或忽略 CRM 死信任务")]
    [ProducesResponseType<CrmQueueItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CrmQueueItem>> Action(
        CrmQueueActionDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await crmService.ApplyQueueActionAsync(ResolveActor(), request.ToCommand(), cancellationToken));
    }

    private CrmAdminActor ResolveActor()
    {
        if (currentTenant.TenantId is null || currentUser.UserId is null)
            throw new CrmException("CRM admin actor was not resolved.", "crm_access_denied");

        return new CrmAdminActor(currentTenant.TenantId.Value, currentUser.UserId.Value);
    }
}