package mongotest

import (
	"context"
	"fmt"
	"sync"

	"github.com/pfeifferj/container-mom-go/pkg/operator/mongodb/api"
	"go.mongodb.org/mongo-driver/mongo"
)

var _ api.Interface = (*MockClient)(nil)

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

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

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

	deployments := make([]api.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) (*api.MongoDeployment, error) {
	m.mu.RLock()
	defer m.mu.RUnlock()

	if d, ok := m.deployments[id]; ok {
		return &d, nil
	}
	return nil, fmt.Errorf("deployment not found")
}

func (m *MockClient) CreateDeployment(ctx context.Context, deployment *api.MongoDeployment) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.deployments[deployment.ID] = *deployment
	return nil
}

func (m *MockClient) UpdateDeployment(ctx context.Context, deployment *api.MongoDeployment) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.deployments[deployment.ID] = *deployment
	return nil
}

func (m *MockClient) DeleteDeployment(ctx context.Context, id string) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	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]api.MongoDeployment)
	return nil
}

func (m *MockClient) GetClient() *mongo.Client {
	return nil
}

func (m *MockClient) Disconnect(ctx context.Context) error {
	return nil
}

func (m *MockClient) Database(name string) *mongo.Database {
	return nil
}
