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.Application.App.Tenants.Queries;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;

namespace TakeoutSaaS.AdminApi.Controllers;

/// <summary>
/// 公域租户自助入住接口。
/// </summary>
[ApiVersion("1.0")]
[AllowAnonymous]
[EnableRateLimiting("public-self-service")]
[Route("api/public/v{version:apiVersion}/tenants")]
public sealed class PublicTenantsController(IMediator mediator) : BaseApiController
{
    /// <summary>
    /// 自助注册租户并生成初始管理员。
    /// </summary>
    /// <param name="command">自助注册命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>注册结果（含临时密码）。</returns>
    [HttpPost("self-register")]
    [ProducesResponseType(typeof(ApiResponse<SelfRegisterResultDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<SelfRegisterResultDto>> SelfRegister(
        [FromBody, Required] SelfRegisterTenantCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 执行自助注册
        var result = await mediator.Send(command, cancellationToken);
        return ApiResponse<SelfRegisterResultDto>.Ok(result);
    }

    /// <summary>
    /// 自助提交或更新实名资料。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="command">实名资料。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>实名资料结果。</returns>
    [HttpPost("{tenantId:long}/verification")]
    [ProducesResponseType(typeof(ApiResponse<TenantVerificationDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<TenantVerificationDto>> SubmitVerification(
        long tenantId,
        [FromBody, Required] SubmitTenantVerificationCommand command,
        CancellationToken cancellationToken)
    {
        // 1. 绑定租户 ID
        var merged = command with { TenantId = tenantId };
        // 2. 提交实名
        var result = await mediator.Send(merged, cancellationToken);
        return ApiResponse<TenantVerificationDto>.Ok(result);
    }

    /// <summary>
    /// 查询租户入住进度。
    /// </summary>
    /// <param name="tenantId">租户 ID。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>入住进度。</returns>
    [HttpGet("{tenantId:long}/status")]
    [ProducesResponseType(typeof(ApiResponse<TenantProgressDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<TenantProgressDto>> Progress(long tenantId, CancellationToken cancellationToken)
    {
        // 1. 查询进度
        var query = new GetTenantProgressQuery { TenantId = tenantId };
        var result = await mediator.Send(query, cancellationToken);
        return ApiResponse<TenantProgressDto>.Ok(result);
    }
}
