#include "biz_lock.h"

#include "common/spdlog/logging.h"

namespace zsy
{
    BizLock::BizLock() : destroyed(false)
    {
    }

    BizLock::~BizLock()
    {
        destroyed = true;
        std::lock_guard lock(locksMtx);
        locks.clear();
    }

    std::unique_ptr<BizLockHeader> BizLock::lock(const std::string &bizId)
    {
        if (bizId.empty())
        {
            LOGGER_ERROR("加锁失败 bizId 为空");
            return nullptr;
        }
        std::lock_guard lock(locksMtx);
        if (!destroyed && !locks.contains(bizId))
        {
            locks.insert(bizId);
            return std::make_unique<BizLockHeader>(bizId, this);
        }
        return nullptr;
    }

    void BizLock::unlock(const std::string &bizId)
    {
        std::lock_guard lock(locksMtx);
        if (const auto it = locks.find(bizId); it != locks.end())
        {
            locks.erase(it);
        }
    }

    BizLockHeader::BizLockHeader(const std::string &bizId, BizLock *bizLock)
        : bizId(bizId), bizLock(bizLock)
    {
    }

    BizLockHeader::~BizLockHeader()
    {
        if (bizLock)
        {
            bizLock->unlock(bizId);
            bizLock = nullptr;
        }
    }
} // zsy