package cn.novalon.gym.manage.member.handler;

import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 分布式锁服务（简化版，使用本地锁）
 * 
 * @author 付嘉
 * @date 2026-05-27
 */
@Component
public class DistributedLockService {

    private final ConcurrentHashMap<String, ReentrantLock> locks = new ConcurrentHashMap<>();

    /**
     * 执行带锁的操作（业务操作）
     */
    public <T> Mono<T> executeWithLock(String userId, String cardType, Mono<T> operation) {
        String lockKey = "lock:member:card:operation:" + userId + ":" + cardType;
        ReentrantLock lock = locks.computeIfAbsent(lockKey, k -> new ReentrantLock());

        lock.lock();
        try {
            return operation.doFinally(signalType -> lock.unlock());
        } catch (Exception e) {
            lock.unlock();
            return Mono.error(e);
        }
    }

    /**
     * 执行带锁的操作（通用/定时任务）
     */
    public <T> Mono<T> executeWithLock(String lockKey, Mono<T> operation) {
        ReentrantLock lock = locks.computeIfAbsent(lockKey, k -> new ReentrantLock());

        lock.lock();
        try {
            return operation.doFinally(signalType -> lock.unlock());
        } catch (Exception e) {
            lock.unlock();
            return Mono.error(e);
        }
    }
}
