package shop.alien.util.type;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.LifeCollect;
import shop.alien.entity.store.LifeUser;
import shop.alien.mapper.LifeUserMapper;

/**
 * life_collect 查询条件：将前端 user_{phone}/store_{phone}/lawyer_{phone} 或数字用户 id 解析为 type + refId 后查询。
 */
public final class LifeCollectIdentityQuery {

    private static final int TYPE_USER = 1;

    private LifeCollectIdentityQuery() {
    }

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

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

        public String getLegacyUserId() {
            return legacyUserId;
        }

        public Integer getUserType() {
            return userType;
        }

        public Integer getRefId() {
            return refId;
        }

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

    /**
     * 解析收藏人标识：支持 user_/store_/lawyer_ 前缀、裸手机号、life_user 数字主键。
     */
    public static Scope resolve(String userIdKey, TypeUtil typeUtil) {
        if (!StringUtils.hasText(userIdKey)) {
            return new Scope(userIdKey, null, null);
        }
        String key = userIdKey.trim();
        if (typeUtil != null && !typeUtil.containsUnderscore(key)) {
            try {
                int refId = Integer.parseInt(key);
                return new Scope(key, TYPE_USER, refId);
            } catch (NumberFormatException ignored) {
                key = "user_" + key;
            }
        }
        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);
    }

    /**
     * 已知 life_user 主键时直接构造收藏人 scope（type=1）。
     */
    public static Scope fromLifeUserId(Integer lifeUserId) {
        if (lifeUserId == null) {
            return new Scope(null, null, null);
        }
        return new Scope(String.valueOf(lifeUserId), TYPE_USER, lifeUserId);
    }

    public static void applyUserSide(LambdaQueryWrapper<LifeCollect> wrapper, Scope scope) {
        if (scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeCollect::getUserIdUserType, scope.getUserType())
                .eq(LifeCollect::getUserIdRefId, scope.getRefId());
    }

    public static void applyUserSide(LambdaUpdateWrapper<LifeCollect> wrapper, Scope scope) {
        if (scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq(LifeCollect::getUserIdUserType, scope.getUserType())
                .eq(LifeCollect::getUserIdRefId, scope.getRefId());
    }

    public static void applyUserSide(QueryWrapper<LifeCollect> wrapper, Scope scope) {
        if (scope == null || !scope.hasTypeRef()) {
            return;
        }
        wrapper.eq("user_id_user_type", scope.getUserType())
                .eq("user_id_ref_id", scope.getRefId());
    }

    /**
     * 写入收藏记录时解析 user_id 并填充 user_id_user_type、user_id_ref_id（不改变前端入参 user_id 字符串）。
     */
    public static void fillIdentityOnCollect(LifeCollect lifeCollect, TypeUtil typeUtil, LifeUserMapper lifeUserMapper) {
        if (lifeCollect == null || !StringUtils.hasText(lifeCollect.getUserId())) {
            return;
        }
        String userId = lifeCollect.getUserId().trim();
        if (typeUtil != null && !typeUtil.containsUnderscore(userId)) {
            try {
                LifeUser lifeUser = lifeUserMapper.selectById(Integer.parseInt(userId));
                if (lifeUser != null && StringUtils.hasText(lifeUser.getUserPhone())) {
                    userId = "user_" + lifeUser.getUserPhone();
                    lifeCollect.setUserId(userId);
                }
            } catch (NumberFormatException ignored) {
                // 裸手机号，保持原样由 resolve 处理
            }
        }
        Scope scope = resolve(userId, typeUtil);
        if (scope.hasTypeRef()) {
            lifeCollect.setUserIdUserType(scope.getUserType());
            lifeCollect.setUserIdRefId(scope.getRefId());
        }
    }
}
