using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Application.App.Merchants.Queries;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
using TakeoutSaaS.Shared.Web.Api;
using TakeoutSaaS.TenantApi.Services;

namespace TakeoutSaaS.TenantApi.Controllers;

/// <summary>
/// 租户端商户中心。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[Route("api/tenant/v{version:apiVersion}/merchant")]
public sealed class MerchantController(
    IMediator mediator,
    ITenantProvider tenantProvider,
    GeoLocationOrchestrator geoLocationOrchestrator) : BaseApiController
{
    /// <summary>
    /// 获取当前登录用户对应的商户中心信息。
    /// </summary>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>商户中心聚合信息。</returns>
    [HttpGet("info")]
    [ProducesResponseType(typeof(ApiResponse<CurrentMerchantCenterDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<CurrentMerchantCenterDto>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<CurrentMerchantCenterDto>> GetInfo(CancellationToken cancellationToken)
    {
        // 1. 查询当前商户中心信息
        var info = await mediator.Send(new GetCurrentMerchantCenterQuery(), cancellationToken);

        // 2. 返回聚合信息
        return ApiResponse<CurrentMerchantCenterDto>.Ok(info);
    }

    /// <summary>
    /// 更新当前商户基础信息。
    /// </summary>
    /// <param name="request">更新请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>更新结果。</returns>
    [HttpPost("update")]
    [ProducesResponseType(typeof(ApiResponse<UpdateMerchantResultDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<UpdateMerchantResultDto>), StatusCodes.Status401Unauthorized)]
    [ProducesResponseType(typeof(ApiResponse<UpdateMerchantResultDto>), StatusCodes.Status422UnprocessableEntity)]
    public async Task<ApiResponse<UpdateMerchantResultDto>> Update(
        [FromBody] UpdateCurrentMerchantRequest request,
        CancellationToken cancellationToken)
    {
        var merchantId = StoreApiHelpers.ParseRequiredSnowflake(request.Id, nameof(request.Id));
        var result = await mediator.Send(new UpdateMerchantCommand
        {
            MerchantId = merchantId,
            Name = request.Name,
            LicenseNumber = request.LicenseNumber,
            LegalRepresentative = request.LegalRepresentative,
            RegisteredAddress = request.RegisteredAddress,
            ContactPhone = request.ContactPhone,
            ContactEmail = request.ContactEmail
        }, cancellationToken);

        if (result is null)
        {
            return ApiResponse<UpdateMerchantResultDto>.Error(ErrorCodes.NotFound, "商户不存在");
        }

        return ApiResponse<UpdateMerchantResultDto>.Ok(result);
    }

    /// <summary>
    /// 手动重试当前商户地理定位。
    /// </summary>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>重试结果。</returns>
    [HttpPost("geocode/retry")]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status401Unauthorized)]
    public async Task<ApiResponse<object>> RetryCurrentMerchantGeocode(CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        if (tenantId <= 0)
        {
            return ApiResponse<object>.Error(ErrorCodes.BadRequest, "缺少租户标识");
        }

        var currentMerchant = await mediator.Send(new GetCurrentMerchantCenterQuery(), cancellationToken);
        var merchantId = currentMerchant.Merchant.Id;
        var success = await geoLocationOrchestrator.RetryMerchantAsync(tenantId, merchantId, cancellationToken);
        if (!success)
        {
            return ApiResponse<object>.Error(ErrorCodes.NotFound, "商户不存在");
        }

        return ApiResponse<object>.Ok(null);
    }
}

/// <summary>
/// 更新当前商户请求。
/// </summary>
public sealed class UpdateCurrentMerchantRequest
{
    /// <summary>
    /// 商户标识。
    /// </summary>
    public string Id { get; set; } = string.Empty;

    /// <summary>
    /// 商户名称。
    /// </summary>
    public string? Name { get; set; }

    /// <summary>
    /// 营业执照号。
    /// </summary>
    public string? LicenseNumber { get; set; }

    /// <summary>
    /// 法人/负责人。
    /// </summary>
    public string? LegalRepresentative { get; set; }

    /// <summary>
    /// 注册地址。
    /// </summary>
    public string? RegisteredAddress { get; set; }

    /// <summary>
    /// 联系电话。
    /// </summary>
    public string? ContactPhone { get; set; }

    /// <summary>
    /// 联系邮箱。
    /// </summary>
    public string? ContactEmail { get; set; }
}
