package com.usky.issue.service.sync.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.usky.common.core.exception.BusinessException;
import com.usky.issue.service.util.SyncJsonMapper;
import com.usky.issue.domain.SysUser;
import com.usky.issue.mapper.SysUserMapper;
import com.usky.issue.service.enums.SyncTypeEnum;
import com.usky.issue.service.sync.SyncDataApplier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户同步应用到 sys_user
 *
 * @author fyc
 * @date 2026-06-29
 */
@Slf4j
@Component
public class UserSyncDataApplier implements SyncDataApplier {

    private static final com.fasterxml.jackson.databind.ObjectMapper OBJECT_MAPPER = SyncJsonMapper.INSTANCE;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public boolean supports(String tableName) {
        return SyncTypeEnum.USER.getCode().equalsIgnoreCase(tableName);
    }

    @Override
    public void apply(Integer tenantId, String operation, String businessPayload) throws Exception {
        if (tenantId == null) {
            throw new BusinessException("用户同步缺少租户ID");
        }
        SysUser user = OBJECT_MAPPER.readValue(businessPayload, SysUser.class);
        if (user.getUserId() == null) {
            throw new BusinessException("用户同步缺少 userId");
        }
        if (user.getTenantId() != null && !tenantId.equals(user.getTenantId())) {
            throw new BusinessException("用户租户不匹配，拒绝同步 userId=" + user.getUserId());
        }
        user.setTenantId(tenantId);

        if ("DELETE".equalsIgnoreCase(operation)) {
            softDeleteUser(user.getUserId(), tenantId);
            return;
        }

        if ("2".equals(user.getDelFlag())) {
            softDeleteUser(user.getUserId(), tenantId);
            return;
        }

        SysUser exist = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserId, user.getUserId())
                .eq(SysUser::getTenantId, tenantId));
        if (exist == null) {
            sysUserMapper.insert(user);
            log.debug("用户同步插入 userId={}, tenantId={}", user.getUserId(), tenantId);
        } else {
            sysUserMapper.updateById(user);
            log.debug("用户同步更新 userId={}, tenantId={}", user.getUserId(), tenantId);
        }
    }

    private void softDeleteUser(Long userId, Integer tenantId) {
        sysUserMapper.update(null, new LambdaUpdateWrapper<SysUser>()
                .eq(SysUser::getUserId, userId)
                .eq(SysUser::getTenantId, tenantId)
                .set(SysUser::getDelFlag, "2"));
        log.debug("用户同步软删除 userId={}, tenantId={}", userId, tenantId);
    }
}
