package mongotest

import (
	"context"
	"sync"

	"github.com/pfeifferj/container-mom-go/pkg/operator/mongodb"
)

// MockClient implements mongodb.Interface for testing
type MockClient struct {
	deployments map[string]mongodb.MongoDeployment
	mu          sync.RWMutex
}

// NewMockClient creates a new mock MongoDB client
func NewMockClient() *MockClient {
	return &MockClient{
		deployments: make(map[string]mongodb.MongoDeployment),
	}
}

func (m *MockClient) ListDeployments(ctx context.Context) ([]mongodb.MongoDeployment, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()

	deployments := make([]mongodb.MongoDeployment, 0, len(m.deployments))
	for _, d := range m.deployments {
		deployments = append(deployments, d)
	}
	return deployments, nil
}

func (m *MockClient) GetDeployment(ctx context.Context, id string) (*mongodb.MongoDeployment, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()

	if d, ok := m.deployments[id]; ok {
		return &d, nil
	}
	return nil, mongodb.ErrDeploymentNotFound
}

func (m *MockClient) CreateDeployment(ctx context.Context, deployment *mongodb.MongoDeployment) error {
	m.mu.Lock()
	defer m.mu.Unlock()

	m.deployments[deployment.ID] = *deployment
	return nil
}

func (m *MockClient) UpdateDeployment(ctx context.Context, deployment *mongodb.MongoDeployment) error {
	m.mu.Lock()
	defer m.mu.Unlock()

	if _, ok := m.deployments[deployment.ID]; !ok {
		return mongodb.ErrDeploymentNotFound
	}
	m.deployments[deployment.ID] = *deployment
	return nil
}

func (m *MockClient) DeleteDeployment(ctx context.Context, id string) error {
	m.mu.Lock()
	defer m.mu.Unlock()

	if _, ok := m.deployments[id]; !ok {
		return mongodb.ErrDeploymentNotFound
	}
	delete(m.deployments, id)
	return nil
}

func (m *MockClient) DeleteAllDeployments(ctx context.Context) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.deployments = make(map[string]mongodb.MongoDeployment)
	return nil
}
