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

namespace Tiku.Api.Controllers;

[ApiController]
[Tags("租户端-交易运营")]
[Authorize(Policy = BackendPermissions.TenantCommerceOperate)]
[RequireSaasFeature(SaasFeatureCatalog.StudentStore)]
[Produces("application/json")]
[Route("api/tenant/commerce")]
public sealed class ActivationCodeAdministrationController(
    IActivationCodeAdministrationService service,
    CommerceAdminActorResolver actorResolver) : ControllerBase
{
    [HttpPost("code-batches")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("创建兑换码批次")]
    [ProducesResponseType<CodeBatchItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CodeBatchItem>> CreateCodeBatch(
        CreateCodeBatchDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.CreateCodeBatchAsync(
            actorResolver.Resolve(),
            request.ToCommand(),
            cancellationToken));
    }

    [HttpGet("activation-codes")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("查询兑换码")]
    [ProducesResponseType<ActivationCodeList>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ActivationCodeList>> ActivationCodes(
        [FromQuery] TenantCommerceQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetActivationCodesAsync(
            actorResolver.Resolve(),
            actorResolver.ToQuery(query),
            cancellationToken));
    }

    [HttpPost("activation-codes/redeem")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("后台核销兑换码")]
    [ProducesResponseType<ActivationCodeItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<ActivationCodeItem>> RedeemActivationCode(
        RedeemActivationCodeDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.RedeemActivationCodeAsync(
            actorResolver.Resolve(),
            request.ToCommand(),
            cancellationToken));
    }
}
