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 RefundAdministrationController(
    IRefundAdministrationService service,
    CommerceAdminActorResolver actorResolver) : ControllerBase
{
    [HttpGet("refunds")]
    [EndpointSummary("查询退款申请")]
    [ProducesResponseType<TenantRefundList>(StatusCodes.Status200OK)]
    public async Task<ActionResult<TenantRefundList>> Refunds(
        [FromQuery] TenantCommerceQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetRefundsAsync(
            actorResolver.Resolve(),
            actorResolver.ToQuery(query),
            cancellationToken));
    }

    [HttpPost("refunds")]
    [EndpointSummary("创建退款申请")]
    [ProducesResponseType<CommerceRefundRequest>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CommerceRefundRequest>> CreateRefund(
        CreateRefundRequestDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.CreateRefundRequestAsync(
            actorResolver.Resolve(),
            request.ToCommand(),
            cancellationToken));
    }

    [HttpPost("refunds/status")]
    [EndpointSummary("更新退款状态")]
    [ProducesResponseType<CommerceRefundRequest>(StatusCodes.Status200OK)]
    public async Task<ActionResult<CommerceRefundRequest>> UpdateRefundStatus(
        UpdateRefundStatusDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpdateRefundStatusAsync(
            actorResolver.Resolve(),
            request.ToCommand(),
            cancellationToken));
    }

    [HttpGet("refunds/{refundRequestId:guid}/events")]
    [EndpointSummary("查询退款事件")]
    [ProducesResponseType<TenantRefundEventList>(StatusCodes.Status200OK)]
    public async Task<ActionResult<TenantRefundEventList>> RefundEvents(
        Guid refundRequestId,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetRefundEventsAsync(
            actorResolver.Resolve(),
            refundRequestId,
            cancellationToken));
    }
}
