package repository

import (
	"context"

	redislib "gateway/internal/library/redis"
	authdomain "gateway/internal/model/auth/domain"
	domrepo "gateway/internal/model/auth/domain/repository"
)

type redisInviteConsumeLock struct {
	client *redislib.Client
}

// NewRedisInviteConsumeLock creates a Redis-backed invite consume lock.
func NewRedisInviteConsumeLock(client *redislib.Client) domrepo.InviteConsumeLock {
	if client == nil || client.Zero() == nil {
		panic("auth: redis client is required for invite consume lock")
	}
	return &redisInviteConsumeLock{client: client}
}

func (s *redisInviteConsumeLock) TryLock(ctx context.Context, tenantID, codeHash string) (bool, error) {
	key := authdomain.InviteConsumeLockRedisKey(tenantID, codeHash)
	ok, err := s.client.Zero().SetnxExCtx(ctx, key, "1", authdomain.InviteConsumeLockTTLSeconds())
	if err != nil {
		return false, err
	}
	return ok, nil
}

func (s *redisInviteConsumeLock) Unlock(ctx context.Context, tenantID, codeHash string) error {
	key := authdomain.InviteConsumeLockRedisKey(tenantID, codeHash)
	_, err := s.client.Zero().DelCtx(ctx, key)
	return err
}

var _ domrepo.InviteConsumeLock = (*redisInviteConsumeLock)(nil)
