package user

import (
	"context"

	"github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/pkg/tool"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type familyScopeHelper struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func newFamilyScopeHelper(ctx context.Context, svcCtx *svc.ServiceContext) *familyScopeHelper {
	return &familyScopeHelper{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (h *familyScopeHelper) resolveScopedUserIds(currentUserId int64) ([]int64, error) {
	familyId, err := h.getCurrentFamilyId(currentUserId)
	if err != nil {
		return nil, err
	}
	if familyId == 0 {
		return []int64{currentUserId}, nil
	}

	var userIds []int64
	err = h.svcCtx.DB.WithContext(h.ctx).
		Model(&user.UserFamilyMember{}).
		Joins("JOIN user_family ON user_family.id = user_family_member.family_id AND user_family.deleted_at IS NULL AND user_family.status = ?", user.FamilyStatusActive).
		Where("user_family_member.family_id = ? AND user_family_member.status = ?", familyId, user.FamilyMemberActive).
		Pluck("user_family_member.user_id", &userIds).Error
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query family members failed")
	}
	if len(userIds) == 0 {
		return []int64{currentUserId}, nil
	}
	if !tool.Contains(userIds, currentUserId) {
		userIds = append(userIds, currentUserId)
	}
	return tool.RemoveDuplicateElements(userIds...), nil
}

func (h *familyScopeHelper) getCurrentFamilyId(currentUserId int64) (int64, error) {
	var relation user.UserFamilyMember
	err := h.svcCtx.DB.WithContext(h.ctx).
		Model(&user.UserFamilyMember{}).
		Select("user_family_member.family_id").
		Joins("JOIN user_family ON user_family.id = user_family_member.family_id AND user_family.deleted_at IS NULL AND user_family.status = ?", user.FamilyStatusActive).
		Where("user_family_member.user_id = ? AND user_family_member.status = ?", currentUserId, user.FamilyMemberActive).
		First(&relation).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return 0, nil
		}
		return 0, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query current family failed")
	}
	return relation.FamilyId, nil
}
