// #region ConfigTabFormColumnsTest [C:2] [TYPE Module] [SEMANTICS test,translate,config,columns,datasource]
// @BRIEF Verify ConfigTabForm columns fetch behavior — skips fetch when columns already loaded,
//        triggers fetch when columns array is empty.
// @RELATION BINDS_TO -> [ConfigTabForm]
// @TEST_CONTRACT: availableColumns populated -> fetchDatasourceColumns NOT called on mount
// @TEST_CONTRACT: availableColumns empty -> fetchDatasourceColumns IS called on mount
// @TEST_EDGE: no datasourceId -> fetch skipped even with empty columns
// @TEST_EDGE: no environmentId -> fetch skipped even with empty columns

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from '@testing-library/svelte';
import ConfigTabForm from '../ConfigTabForm.svelte';

// ── Hoisted mock factories (must be before vi.mock) ────────────────
const mockGetAllowedLanguages = vi.hoisted(() => vi.fn().mockResolvedValue(['en', 'ru']));
const mockFetchDatasourceColumns = vi.hoisted(() => vi.fn());
const mockFetchDatasources = vi.hoisted(() => vi.fn());

// ── i18n mock ─────────────────────────────────────────────────────
const mockTranslations = {
	translate: {
		config: {
			basic_info: 'Basic Info',
			name: 'Name',
			description: 'Description',
			name_placeholder: 'Enter name',
			description_placeholder: 'Enter description',
			help_name: 'Name of the job',
			help_description: 'Optional description',
			datasource: 'Datasource',
			environment: 'Environment',
			help_environment: 'Select the target environment',
			select_environment: '-- Select --',
			datasource_id: 'Datasource Search',
			help_datasource: 'Find and select a datasource',
			datasource_search_placeholder: 'Search datasets...',
			detected_dialect: 'Detected: {dialect}',
			available_columns: 'Available columns ({count})',
			virtual: 'virtual',
			virtual_column_warning: 'Virtual column {col}',
			column_mapping: 'Column Mapping',
			translation_column: 'Translation Column',
			help_translation_column: 'Select the column to translate',
			select_column: '-- Select column --',
			key_columns: 'Key Columns',
			help_key_columns: 'Select key columns for row matching',
			clear_all: 'Clear all',
			add_key_column: '+ Add key column',
		}
	}
};

vi.mock('$lib/i18n/index.svelte.js', () => ({
	getT: () => mockTranslations,
	t: {
		subscribe: (fn) => {
			fn(mockTranslations);
			return () => {};
		}
	},
	_: (key) => key,
}));

// ── Languages mock ────────────────────────────────────────────────
vi.mock('$lib/i18n/languages.js', () => ({
	ALL_LANGUAGES: [{ code: 'en', name: 'English' }, { code: 'ru', name: 'Russian' }],
	filterLanguages: (codes) => [{ code: 'en', name: 'English' }],
}));

// ── API mocks ─────────────────────────────────────────────────────
vi.mock('$lib/api.js', () => ({
	api: {
		getAllowedLanguages: mockGetAllowedLanguages,
	}
}));

vi.mock('$lib/api/translate.js', () => ({
	fetchDatasourceColumns: mockFetchDatasourceColumns,
	fetchDatasources: mockFetchDatasources,
}));

// ── CoT logger mock ───────────────────────────────────────────────
vi.mock('$lib/cot-logger', () => ({
	log: vi.fn(),
	setTraceId: vi.fn(),
	getTraceId: vi.fn(() => 'test-trace-id'),
}));

// #region ConfigTabFormColumnsTest.Describe [C:2] [TYPE Test]
// @BRIEF Test the columns fetch $effect guard — availableColumns.length check.
describe('ConfigTabForm — columns fetch guard', () => {
	beforeEach(() => {
		vi.clearAllMocks();
	});

	// #region test_skips_columns_fetch_when_already_loaded [C:2] [TYPE Test]
	// @BRIEF When availableColumns has items, the effect should not call fetchDatasourceColumns.
	it('skips columns fetch when columns already loaded', async () => {
		render(ConfigTabForm, {
			props: {
				datasourceId: 'ds-1',
				environmentId: 'env-1',
				availableColumns: [
					{ name: 'id', type: 'integer' },
					{ name: 'name', type: 'varchar' },
				],
			},
		});

		// Let $effect and async operations settle
		await new Promise(r => setTimeout(r, 50));

		expect(mockFetchDatasourceColumns).not.toHaveBeenCalled();
	});
	// #endregion test_skips_columns_fetch_when_already_loaded

	// #region test_fetches_columns_when_empty [C:2] [TYPE Test]
	// @BRIEF When availableColumns is empty [] and datasourceId+environmentId are set,
	//        the effect MUST call fetchDatasourceColumns.
	it('fetches columns when availableColumns is empty', async () => {
		mockFetchDatasourceColumns.mockResolvedValue([
			{ name: 'id', type: 'integer' },
		]);

		render(ConfigTabForm, {
			props: {
				datasourceId: 'ds-1',
				environmentId: 'env-1',
				availableColumns: [],
			},
		});

		// Let $effect and async operations settle
		await new Promise(r => setTimeout(r, 50));

		expect(mockFetchDatasourceColumns).toHaveBeenCalledTimes(1);
		expect(mockFetchDatasourceColumns).toHaveBeenCalledWith('ds-1', 'env-1');
	});
	// #endregion test_fetches_columns_when_empty
});
// #endregion ConfigTabFormColumnsTest.Describe
// #endregion ConfigTabFormColumnsTest
