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 PaymentConfigurationController(
    IPaymentConfigurationService service,
    CommerceAdminActorResolver actorResolver) : ControllerBase
{
    [HttpGet("payment-accounts")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("查询租户支付账号")]
    [ProducesResponseType<IReadOnlyCollection<TenantPaymentProviderItem>>(StatusCodes.Status200OK)]
    public async Task<ActionResult<IReadOnlyCollection<TenantPaymentProviderItem>>> PaymentAccounts(
        [FromQuery] TenantCommerceQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetPaymentAccountsAsync(
            actorResolver.Resolve(),
            actorResolver.ToQuery(query),
            cancellationToken));
    }

    [HttpPut("payment-accounts")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("新增或更新租户支付账号")]
    [ProducesResponseType<TenantPaymentProviderItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<TenantPaymentProviderItem>> UpsertPaymentAccount(
        UpsertPaymentAccountDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpsertPaymentAccountAsync(
            actorResolver.Resolve(),
            request.ToCommand(),
            cancellationToken));
    }

    [HttpPut("secrets")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("写入或轮换租户密钥")]
    [ProducesResponseType<TenantSecretItem>(StatusCodes.Status200OK)]
    public async Task<ActionResult<TenantSecretItem>> UpsertSecret(
        UpsertTenantSecretDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpsertTenantSecretAsync(
            actorResolver.Resolve(),
            request.ToCommand(),
            cancellationToken));
    }
}
