package organization

import "context"

type preparedFeishuDirectoryImport struct {
	organizationID                  string
	settings                        OrganizationSettingsView
	identityNamespace               string
	snapshot                        feishuDirectorySnapshot
	materializedUserIDsByExternalID map[string]string
}

type preparedFeishuDirectoryImportKey struct{}

func (store *Store) preflightTxStore() TxStore {
	return TxStore{
		db:                            store.db,
		core:                          store.core,
		feishuBaseURL:                 store.feishuBaseURL,
		feishuHTTPClient:              store.feishuHTTPClient,
		feishuAppID:                   store.feishuAppID,
		feishuAppSecret:               store.feishuAppSecret,
		feishuCredentialEncryptionKey: append([]byte(nil), store.feishuCredentialEncryptionKey...),
	}
}

func (store *Store) prepareFeishuDirectoryImport(ctx context.Context, settings OrganizationSettingsView, identityNamespace string, client FeishuDirectoryClient) (context.Context, error) {
	if client == nil {
		return ctx, badRequest("feishu directory client is required")
	}

	helper := store.preflightTxStore()
	snapshot, err := collectFeishuDirectorySnapshot(ctx, client, resolveFeishuRootDepartmentID(settings.Feishu.RootDepartmentID))
	if err != nil {
		return ctx, err
	}
	materializedUserIDsByExternalID, err := helper.materializeFeishuDirectoryUsers(ctx, settings, identityNamespace, snapshot)
	if err != nil {
		return ctx, err
	}

	return context.WithValue(ctx, preparedFeishuDirectoryImportKey{}, preparedFeishuDirectoryImport{
		organizationID:                  settings.OrganizationID,
		settings:                        settings,
		identityNamespace:               identityNamespace,
		snapshot:                        snapshot,
		materializedUserIDsByExternalID: materializedUserIDsByExternalID,
	}), nil
}

func loadPreparedFeishuDirectoryImport(ctx context.Context, organizationID string) (preparedFeishuDirectoryImport, bool) {
	prepared, ok := ctx.Value(preparedFeishuDirectoryImportKey{}).(preparedFeishuDirectoryImport)
	if !ok || prepared.organizationID != organizationID {
		return preparedFeishuDirectoryImport{}, false
	}
	return prepared, true
}
