package app

import (
	"context"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/extension/runner"
	storeapp "github.com/tidbcloud/AgentTeam/internal/store/app"
)

func (fake *fakeStore) GetExtensionProviderConnectionForUser(
	_ context.Context,
	_ string,
	_ string,
	installationID string,
	_ storeapp.ExtensionProviderTarget,
) (storeapp.ExtensionProviderConnectionView, error) {
	fake.mu.Lock()
	defer fake.mu.Unlock()
	fake.lastProviderInstallationID = installationID
	fake.lastProviderOperation = "get"
	return fake.providerConnection, fake.providerConnectionErr
}

func (fake *fakeStore) UpsertExtensionProviderConnectionForUser(
	_ context.Context,
	_ string,
	_ string,
	installationID string,
	_ storeapp.ExtensionProviderTarget,
	credentials map[string]string,
	config runner.ConnectionConfig,
	expectedUpdatedAt *time.Time,
) (storeapp.ExtensionProviderConnectionView, error) {
	fake.mu.Lock()
	defer fake.mu.Unlock()
	fake.lastProviderInstallationID = installationID
	fake.lastProviderOperation = "put"
	fake.lastProviderCredentials = credentials
	fake.lastProviderConfig = config.Clone()
	fake.lastProviderExpectedUpdatedAt = expectedUpdatedAt
	return fake.providerConnection, fake.providerConnectionErr
}

func (fake *fakeStore) DeleteExtensionProviderConnectionForUser(
	_ context.Context,
	_ string,
	_ string,
	installationID string,
	_ storeapp.ExtensionProviderTarget,
) error {
	fake.mu.Lock()
	defer fake.mu.Unlock()
	fake.lastProviderInstallationID = installationID
	fake.lastProviderOperation = "delete"
	return fake.providerConnectionErr
}

func (fake *fakeStore) AuthorizeExtensionProviderConnectionAdmin(
	_ context.Context,
	_ string,
	_ string,
	installationID string,
	_ storeapp.ExtensionProviderTarget,
) error {
	fake.mu.Lock()
	defer fake.mu.Unlock()
	fake.lastProviderInstallationID = installationID
	return fake.providerAuthorizeErr
}

func (fake *fakeStore) ResolveExtensionProviderRuntimeConnection(
	_ context.Context,
	_ string,
	installationID string,
	_ storeapp.ExtensionProviderTarget,
	configContract runner.ConnectionConfigContract,
) (map[string]string, runner.ConnectionConfig, error) {
	fake.mu.Lock()
	defer fake.mu.Unlock()
	fake.lastProviderInstallationID = installationID
	fake.lastProviderOperation = "resolve"
	config := fake.runtimeProviderConfig.Clone()
	if fake.providerConnectionErr != nil {
		return nil, nil, fake.providerConnectionErr
	}
	if err := configContract.Validate(config); err != nil {
		return nil, nil, err
	}
	return fake.runtimeProviderCredentials, config, nil
}
