using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using System.ComponentModel.DataAnnotations;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;

namespace TakeoutSaaS.AdminApi.Controllers;

/// <summary>
/// 公域租户订阅自助接口（需登录，无权限校验）。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[EnableRateLimiting("public-self-service")]
[Route("api/public/v{version:apiVersion}/tenants")]
public sealed class PublicTenantSubscriptionsController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 初次绑定租户订阅（默认 0 个月）。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="body">绑定请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>绑定后的订阅信息。</returns>
    [HttpPost("{tenantId:long}/subscriptions/initial")]
    [ProducesResponseType(typeof(ApiResponse<TenantSubscriptionDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<TenantSubscriptionDto>), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ApiResponse<TenantSubscriptionDto>), StatusCodes.Status403Forbidden)]
    [ProducesResponseType(typeof(ApiResponse<TenantSubscriptionDto>), StatusCodes.Status409Conflict)]
    public async Task<ApiResponse<TenantSubscriptionDto>> BindInitialSubscription(
        long tenantId,
        [FromBody, Required] BindInitialTenantSubscriptionCommand body,
        CancellationToken cancellationToken)
    {
        // 1. 合并路由租户标识
        var command = body with { TenantId = tenantId };

        // 2. 执行初次订阅绑定
        var result = await mediator.Send(command, cancellationToken);

        // 3. 返回绑定结果
        return ApiResponse<TenantSubscriptionDto>.Ok(result);
    }
}

