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 CouponAdministrationController(
    ICouponAdministrationService service,
    CommerceAdminActorResolver actorResolver) : ControllerBase
{
    [HttpGet("coupons")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("查询租户优惠券")]
    [ProducesResponseType<TenantCouponList>(StatusCodes.Status200OK)]
    public async Task<ActionResult<TenantCouponList>> Coupons(
        [FromQuery] TenantCommerceQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetCouponsAsync(
            actorResolver.Resolve(),
            actorResolver.ToQuery(query),
            cancellationToken));
    }

    [HttpPut("coupons")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("新增或更新租户优惠券")]
    [ProducesResponseType<object>(StatusCodes.Status200OK)]
    public async Task<ActionResult<object>> UpsertCoupon(
        UpsertTenantCouponDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await service.UpsertCouponAsync(
            actorResolver.Resolve(),
            request.ToCommand(),
            cancellationToken));
    }

    [HttpGet("coupons/redemptions")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("查询优惠券领取和核销记录")]
    [ProducesResponseType<TenantCouponRedemptionList>(StatusCodes.Status200OK)]
    public async Task<ActionResult<TenantCouponRedemptionList>> CouponRedemptions(
        [FromQuery] TenantCommerceQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetCouponRedemptionsAsync(
            actorResolver.Resolve(),
            actorResolver.ToQuery(query),
            cancellationToken));
    }

    [HttpGet("coupons/report")]
    [Authorize(Policy = TikuPolicies.TenantCommerceOperateAllScope)]
    [EndpointSummary("查询优惠券基础报表")]
    [ProducesResponseType<TenantCouponReport>(StatusCodes.Status200OK)]
    public async Task<ActionResult<TenantCouponReport>> CouponReport(
        [FromQuery] TenantCommerceQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await service.GetCouponReportAsync(
            actorResolver.Resolve(),
            actorResolver.ToQuery(query),
            cancellationToken));
    }
}
