// #region TranslateTargetSchemaApi [C:2] [TYPE Module] [SEMANTICS translate, target-schema, api, validation]
// @BRIEF API client for target table schema validation — checks expected vs actual columns for translation inserts.
// @LAYER API
// @RELATION DEPENDS_ON -> [ApiModule]
// @POST Returns schema validation result with all_present flag, or a graceful error shape if the API call fails.

import { api } from '$lib/api';

export interface TargetSchemaCheckPayload {
	environment_id: string;
	target_database_id: string;
	target_schema: string;
	target_table: string;
	target_key_cols: string[];
	target_column: string | null;
	translation_column: string | null;
	target_language_column: string | null;
	target_source_column: string | null;
	target_source_language_column: string | null;
}

export interface ColumnInfo {
	name: string;
	data_type: string | null;
	is_nullable: boolean;
}

export interface TargetSchemaCheckResponse {
	table_exists: boolean;
	error: string | null;
	expected_columns: ColumnInfo[];
	actual_columns: ColumnInfo[];
	missing_columns: ColumnInfo[];
	extra_columns: ColumnInfo[];
	all_present: boolean;
}

// #region checkTargetTableSchema [C:2] [TYPE Function] [SEMANTICS translate, target-schema, check, validate]
// @BRIEF Check target table schema — validate expected vs actual columns for translation inserts.
// @PRE payload contains all required target table configuration fields.
// @POST Returns schema validation result with all_present flag.
//      On API failure, returns a graceful error shape (table_exists=false, error=message).
// @SIDE_EFFECT Sends POST request to validate target schema.
// @RELATION DEPENDS_ON -> [ApiModule.postApi]
// @RATIONALE On API failure, returns a graceful error object instead of throwing,
//            because the schema check is advisory — the caller should still allow the
//            user to proceed with a warning instead of blocking the flow entirely.
export async function checkTargetTableSchema(payload: TargetSchemaCheckPayload): Promise<TargetSchemaCheckResponse> {
	try {
		return await api.postApi<TargetSchemaCheckResponse>('/translate/check-target-schema', payload);
	} catch (error) {
		const message =
			(error && typeof (error as Error).message === 'string' && (error as Error).message) ||
			(typeof error === 'string' && error) ||
			'Failed to check target table schema';
		return {
			table_exists: false,
			error: message,
			expected_columns: [],
			actual_columns: [],
			missing_columns: [],
			extra_columns: [],
			all_present: false,
		};
	}
}
// #endregion checkTargetTableSchema
// #endregion TranslateTargetSchemaApi
