package user

import (
	"context"

	commonLogic "github.com/perfect-panel/server/internal/logic/common"
	"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 GetSubscribeStatusLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetSubscribeStatusLogic) GetSubscribeStatus(req *types.GetSubscribeStatusRequest) (*types.GetSubscribeStatusResponse, error) {
	// 取当前用户
	u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
	if !ok || u == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "invalid user token")
	}

	// 1. 查 device 认证方式有没有套餐
	deviceStatus := false
	if len(u.UserDevices) > 0 {
		if dev, err := l.svcCtx.UserModel.FindOneDeviceByIdentifier(l.ctx, u.UserDevices[0].Identifier); err == nil && dev.Id > 0 {
			effectiveUserID := l.resolveEntitlementUserID(dev.UserId)
			subscribes, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, effectiveUserID)
			if err == nil {
				deviceStatus = len(subscribes) > 0
			}
		}
	}

	// 2.根据 req.email 查询 有没有套餐
	emailStatus := false
	if req.Email != "" {
		if auth, err := l.svcCtx.UserModel.FindUserAuthMethodByOpenID(l.ctx, "email", req.Email); err == nil && auth.Id > 0 {
			effectiveUserID := l.resolveEntitlementUserID(auth.UserId)
			subscribes, err := l.svcCtx.UserModel.QueryUserSubscribe(l.ctx, effectiveUserID)
			if err == nil {
				emailStatus = len(subscribes) > 0
			}
		}
	}

	l.Infow("get subscribe status", logger.Field("userId", u.Id), logger.Field("device_status", deviceStatus), logger.Field("email_status", emailStatus))
	return &types.GetSubscribeStatusResponse{
		DeviceStatus: deviceStatus,
		EmailStatus:  emailStatus,
	}, nil
}

func (l *GetSubscribeStatusLogic) resolveEntitlementUserID(userID int64) int64 {
	entitlement, err := commonLogic.ResolveEntitlementUser(l.ctx, l.svcCtx.DB, userID)
	if err != nil {
		l.Errorw("resolve family entitlement failed", logger.Field("user_id", userID), logger.Field("error", err.Error()))
		return userID
	}
	return entitlement.EffectiveUserID
}
