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("租户端-佣金")]
[Authorize(Policy = BackendPermissions.TenantCommissionManage)]
[RequireSaasFeature(SaasFeatureCatalog.ReferralCommission)]
[Produces("application/json")]
[Route("api/tenant/commission")]
public sealed class CommissionController(
    ICommissionService commissionService,
    ICurrentUser currentUser,
    ITenantContext currentTenant) : ControllerBase
{
    [HttpGet("settings")]
    [EndpointSummary("查询佣金配置")]
    public async Task<ActionResult<CommissionSettingsItem>> Settings(CancellationToken cancellationToken)
    {
        return Ok(await commissionService.GetSettingsAsync(ResolveActor(), cancellationToken));
    }

    [HttpPut("settings")]
    [EndpointSummary("保存佣金配置")]
    public async Task<ActionResult<CommissionSettingsItem>> UpdateSettings(UpdateCommissionSettingsDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await commissionService.UpdateSettingsAsync(ResolveActor(), request.ToCommand(), cancellationToken));
    }

    [HttpPut("member-rate")]
    [EndpointSummary("调整成员佣金比例")]
    public async Task<ActionResult<object>> MemberRate(UpdateMemberCommissionRateDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await commissionService.UpdateMemberRateAsync(ResolveActor(), request.ToCommand(),
            cancellationToken));
    }

    [HttpGet("summary")]
    [EndpointSummary("查询佣金统计摘要")]
    public async Task<ActionResult<CommissionSummaryItem>> Summary([FromQuery] CommissionPeriodQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await commissionService.GetSummaryAsync(ResolveActor(), query.ToQuery(), cancellationToken));
    }

    [HttpGet("orders")]
    [EndpointSummary("查询佣金来源订单")]
    public async Task<ActionResult<CommissionList<CommissionSourceItem>>> Orders(
        [FromQuery] CommissionPeriodQueryDto query, CancellationToken cancellationToken)
    {
        return Ok(await commissionService.GetOrdersAsync(ResolveActor(), query.ToQuery(), cancellationToken));
    }

    [HttpGet("settlements")]
    [EndpointSummary("查询佣金结算单")]
    public async Task<ActionResult<CommissionList<CommissionSettlementItemDto>>> Settlements(
        [FromQuery] CommissionSettlementsQueryDto query, CancellationToken cancellationToken)
    {
        return Ok(await commissionService.GetSettlementsAsync(ResolveActor(), query.ToQuery(), cancellationToken));
    }

    [HttpGet("settlements/export")]
    [EndpointSummary("导出佣金结算单")]
    public async Task<ActionResult<CommissionExportItem>> Export([FromQuery] CommissionSettlementExportQueryDto query,
        CancellationToken cancellationToken)
    {
        return Ok(await commissionService.ExportSettlementAsync(ResolveActor(), query.SettlementId, query.Format,
            cancellationToken));
    }

    [HttpPost("settlements/generate")]
    [EndpointSummary("生成佣金结算单")]
    public async Task<ActionResult<CommissionSettlementItemDto>> Generate(GenerateCommissionSettlementDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await commissionService.GenerateSettlementAsync(ResolveActor(), request.ToCommand(),
            cancellationToken));
    }

    [HttpPost("settlements/status")]
    [EndpointSummary("更新佣金结算单状态")]
    public async Task<ActionResult<CommissionSettlementItemDto>> UpdateStatus(
        UpdateCommissionSettlementStatusDto request, CancellationToken cancellationToken)
    {
        return Ok(await commissionService.UpdateSettlementStatusAsync(ResolveActor(), request.ToCommand(),
            cancellationToken));
    }

    [HttpGet("settlements/proofs")]
    [EndpointSummary("查询佣金结算凭证")]
    public async Task<ActionResult<CommissionList<CommissionProofItem>>> Proofs(
        [FromQuery] CommissionSettlementProofQueryDto query, CancellationToken cancellationToken)
    {
        return Ok(await commissionService.GetProofsAsync(ResolveActor(), query.SettlementId, cancellationToken));
    }

    [HttpPost("settlements/proofs")]
    [EndpointSummary("创建佣金结算凭证")]
    public async Task<ActionResult<CommissionProofItem>> CreateProof(CreateCommissionProofDto request,
        CancellationToken cancellationToken)
    {
        return Ok(await commissionService.CreateProofAsync(ResolveActor(), request.ToCommand(), cancellationToken));
    }

    [HttpPost("settlements/proofs/status")]
    [EndpointSummary("更新佣金结算凭证状态")]
    public async Task<ActionResult<CommissionProofItem>> UpdateProofStatus(UpdateCommissionProofStatusDto request,
        CancellationToken cancellationToken)
    {
        return Ok(
            await commissionService.UpdateProofStatusAsync(ResolveActor(), request.ToCommand(), cancellationToken));
    }

    private CommissionAdminActor ResolveActor()
    {
        if (currentTenant.TenantId is null || currentUser.UserId is null)
            throw new CommissionException("Commission admin actor was not resolved.", "commission_access_denied");

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