package mock

import (
	"context"
	"sync"

	"github.com/ocdp/cluster-service/internal/domain/entity"
	"github.com/ocdp/cluster-service/internal/domain/repository"
)

// UserRepositoryMock 用户仓储 Mock 实现（内存存储）
type UserRepositoryMock struct {
	mu    sync.RWMutex
	users map[string]*entity.User // key: user ID
}

// NewUserRepositoryMock 创建 Mock 实现
func NewUserRepositoryMock() repository.UserRepository {
	return &UserRepositoryMock{
		users: make(map[string]*entity.User),
	}
}

func (r *UserRepositoryMock) Create(ctx context.Context, user *entity.User) error {
	r.mu.Lock()
	defer r.mu.Unlock()

	// 检查是否已存在
	for _, u := range r.users {
		if u.Username == user.Username {
			return entity.ErrUserExists
		}
	}

	r.users[user.ID] = user
	return nil
}

func (r *UserRepositoryMock) GetByID(ctx context.Context, id string) (*entity.User, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	user, exists := r.users[id]
	if !exists {
		return nil, entity.ErrUserNotFound
	}

	return user, nil
}

func (r *UserRepositoryMock) GetByUsername(ctx context.Context, username string) (*entity.User, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	for _, user := range r.users {
		if user.Username == username {
			return user, nil
		}
	}

	return nil, entity.ErrUserNotFound
}

func (r *UserRepositoryMock) Update(ctx context.Context, user *entity.User) error {
	r.mu.Lock()
	defer r.mu.Unlock()

	if _, exists := r.users[user.ID]; !exists {
		return entity.ErrUserNotFound
	}

	r.users[user.ID] = user
	return nil
}

func (r *UserRepositoryMock) Delete(ctx context.Context, id string) error {
	r.mu.Lock()
	defer r.mu.Unlock()

	if _, exists := r.users[id]; !exists {
		return entity.ErrUserNotFound
	}

	delete(r.users, id)
	return nil
}

func (r *UserRepositoryMock) List(ctx context.Context) ([]*entity.User, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()

	users := make([]*entity.User, 0, len(r.users))
	for _, user := range r.users {
		users = append(users, user)
	}

	return users, nil
}
