package lock

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"time"
)

type Mutex struct {
	locker *Locker
	ttl    time.Duration
}

func NewMutex(client *redis.Client, ttl time.Duration) *Mutex {
	return &Mutex{
		locker: NewLocker(client, ttl, TryLockInterval),
	}
}

func (c *Mutex) Lock(ctx context.Context, resource string, callback func(ctx context.Context) error) error {
	l := c.locker.GetLock(resource)

	if err := l.Lock(ctx); err != nil {
		return fmt.Errorf("lock failed %s:%w", resource, err)
	}
	defer func() {
		_ = l.Unlock(ctx)
	}()

	return callback(ctx)
}
