package apple

import (
	"context"
	"strings"
	"time"

	"github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/constant"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

type GetStatusLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetStatusLogic {
	return &GetStatusLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetStatusLogic) GetStatus() (*types.GetAppleStatusResponse, error) {
	u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
	if !ok || u == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "invalid access")
	}
	// 查该用户所有状态的订阅，找 IAP 相关的（token 以 iap: 开头）
	subs, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, u.Id, 1)
	if err != nil {
		return &types.GetAppleStatusResponse{Active: false, ExpiresAt: 0, Tier: ""}, nil
	}
	now := time.Now()
	var bestExpire time.Time
	var bestTier string
	for _, sub := range subs {
		if sub == nil {
			continue
		}
		// 仅处理 IAP 创建的订阅（token 以 "iap:" 开头）
		if !strings.HasPrefix(sub.Token, "iap:") {
			continue
		}
		if sub.ExpireTime.After(bestExpire) {
			bestExpire = sub.ExpireTime
			if sub.Subscribe != nil {
				bestTier = sub.Subscribe.Name
			}
		}
	}
	if bestExpire.IsZero() {
		return &types.GetAppleStatusResponse{Active: false, ExpiresAt: 0, Tier: ""}, nil
	}
	active := bestExpire.After(now)
	return &types.GetAppleStatusResponse{
		Active:    active,
		ExpiresAt: bestExpire.Unix(),
		Tier:      bestTier,
	}, nil
}
