package shop.alien.util.type;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.LifeFans;

import java.util.Optional;

/**
 * life_fans 身份解析与查询：将 user_/store_/lawyer_ 前缀 phoneId 解析为 type + refId，
 * 写入 fans_user_type / fans_ref_id / followed_user_type / followed_ref_id；
 * 查询条件仅使用 type + refId（不依赖 fans_id / followed_id 字符串匹配）。
 */
public final class LifeFansIdentityQuery {

    private LifeFansIdentityQuery() {
    }

    public static final class Scope {
        private final String legacyPhoneId;
        private final Integer userType;
        private final Integer refId;

        public Scope(String legacyPhoneId, Integer userType, Integer refId) {
            this.legacyPhoneId = legacyPhoneId;
            this.userType = userType;
            this.refId = refId;
        }

        public String getLegacyPhoneId() {
            return legacyPhoneId;
        }

        public Integer getUserType() {
            return userType;
        }

        public Integer getRefId() {
            return refId;
        }

        public boolean hasTypeRef() {
            return userType != null && refId != null;
        }
    }

    public static Scope resolve(String phoneId, TypeUtil typeUtil) {
        if (!StringUtils.hasText(phoneId)) {
            return new Scope(phoneId, null, null);
        }
        String key = phoneId.trim();
        if (typeUtil != null && typeUtil.containsUnderscore(key)) {
            PhoneTypeIdResult resolved = typeUtil.resolveTypeAndId(key);
            if (resolved != null) {
                return new Scope(key, resolved.getType(), resolved.getId());
            }
        }
        return new Scope(key, null, null);
    }

    /**
     * 写入关注记录时解析 fans_id / followed_id 并填充 type + ref 字段（不改变前端入参字符串）。
     */
    public static void fillIdentityOnFans(LifeFans lifeFans, TypeUtil typeUtil) {
        if (lifeFans == null) {
            return;
        }
        Scope fansScope = resolve(lifeFans.getFansId(), typeUtil);
        if (fansScope.hasTypeRef()) {
            lifeFans.setFansUserType(fansScope.getUserType());
            lifeFans.setFansRefId(fansScope.getRefId());
        }
        Scope followedScope = resolve(lifeFans.getFollowedId(), typeUtil);
        if (followedScope.hasTypeRef()) {
            lifeFans.setFollowedUserType(followedScope.getUserType());
            lifeFans.setFollowedRefId(followedScope.getRefId());
        }
    }

    public static boolean hasCompletePairIdentity(LifeFans lifeFans) {
        return lifeFans != null
                && lifeFans.getFansUserType() != null
                && lifeFans.getFansRefId() != null
                && lifeFans.getFollowedUserType() != null
                && lifeFans.getFollowedRefId() != null;
    }

    /**
     * 回填后校验双方 type + ref 是否齐全；失败时返回错误文案。
     */
    public static Optional<String> validatePairIdentity(LifeFans lifeFans) {
        if (lifeFans == null) {
            return Optional.of("请求参数不能为空：请传入被关注方与粉丝标识");
        }
        if (lifeFans.getFansUserType() == null || lifeFans.getFansRefId() == null) {
            return Optional.of("粉丝方标识（fansId）无法解析为有效用户，请检查格式或用户是否存在");
        }
        if (lifeFans.getFollowedUserType() == null || lifeFans.getFollowedRefId() == null) {
            return Optional.of("被关注方标识（followedId）无法解析为有效用户，请检查格式或用户是否存在");
        }
        return Optional.empty();
    }

    public static void applyFansSide(LambdaQueryWrapper<LifeFans> wrapper, Scope scope) {
        if (scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeFans::getFansUserType, scope.getUserType())
                .eq(LifeFans::getFansRefId, scope.getRefId());
    }

    public static void applyFollowedSide(LambdaQueryWrapper<LifeFans> wrapper, Scope scope) {
        if (scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeFans::getFollowedUserType, scope.getUserType())
                .eq(LifeFans::getFollowedRefId, scope.getRefId());
    }

    public static void applyFansSide(LambdaUpdateWrapper<LifeFans> wrapper, Scope scope) {
        if (scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeFans::getFansUserType, scope.getUserType())
                .eq(LifeFans::getFansRefId, scope.getRefId());
    }

    public static void applyFollowedSide(LambdaUpdateWrapper<LifeFans> wrapper, Scope scope) {
        if (scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeFans::getFollowedUserType, scope.getUserType())
                .eq(LifeFans::getFollowedRefId, scope.getRefId());
    }

    /** 粉丝方 + 被关注方四维匹配（查重、互关等）。 */
    public static void applyPair(LambdaQueryWrapper<LifeFans> wrapper, Scope fansScope, Scope followedScope) {
        applyFansSide(wrapper, fansScope);
        applyFollowedSide(wrapper, followedScope);
    }

    public static void applyPairWithDeleteFlag(LambdaQueryWrapper<LifeFans> wrapper, Scope fansScope, Scope followedScope) {
        wrapper.eq(LifeFans::getDeleteFlag, 0);
        applyPair(wrapper, fansScope, followedScope);
    }
}
