using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Services;

/// <summary>
/// 门店模块请求上下文服务。
/// </summary>
public sealed class StoreContextService(
    ICurrentUserAccessor currentUserAccessor,
    ITenantProvider tenantProvider,
    IHttpContextAccessor httpContextAccessor)
{
    /// <summary>
    /// 读取当前请求所需的用户、租户与商户上下文。
    /// </summary>
    /// <returns>用户 ID、租户 ID、商户 ID。</returns>
    public (long UserId, long TenantId, long MerchantId) GetRequiredContext()
    {
        // 1. 校验登录用户
        var userId = currentUserAccessor.UserId;
        if (userId <= 0)
        {
            throw new BusinessException(ErrorCodes.Unauthorized, "未登录或登录已过期");
        }

        // 2. 校验租户上下文
        var tenantId = tenantProvider.GetCurrentTenantId();
        if (tenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 3. 解析商户上下文
        var merchantId = ResolveMerchantId();
        if (merchantId <= 0)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "当前用户未绑定商户，无法访问门店管理");
        }

        // 4. 返回上下文
        return (userId, tenantId, merchantId);
    }

    private long ResolveMerchantId()
    {
        // 1. 从 JWT Claim 读取商户标识
        var principal = httpContextAccessor.HttpContext?.User;
        var merchantClaim = principal?.FindFirst("merchant_id")?.Value
                            ?? principal?.FindFirst(ClaimTypes.GroupSid)?.Value;

        // 2. 返回解析结果
        return long.TryParse(merchantClaim, out var merchantId) ? merchantId : 0L;
    }
}

