import { browser } from '$app/environment';
import type { key_val } from '$lib/stores/ae_stores';
import { api } from '$lib/api/api';

export interface Data_Store {
	id: string;
	account_id: string;
	code: string;
	name: string;
	type: string;
	for_type?: string | null;
	for_id?: string | null;
	access_read?: string | null;
	access_write?: string | null;
	access_delete?: string | null;
	html?: string | null;
	json?: key_val | null;
	md?: string | null;
	text?: string | null;
	updated_on?: string | null;
	chk_account_id?: string;
	loaded_on?: string;
}

/**
 * Fetches a data_store object by its unique code.
 *
 * @param api_cfg - The API configuration object.
 * @param code - The code of the data store to fetch.
 * @param data_type - The expected data type ('text', 'json', 'html', 'md', 'sql').
 * @param save_idb - Whether to save the fetched data to localStorage.
 * @param timeout - The request timeout in milliseconds.
 * @param log_lvl - The logging level.
 * @returns The data from the data store (e.g., text content or JSON object).
 */
export async function load_ae_obj_by_code__data_store({
	api_cfg,
	code,
	data_type = 'text',
	save_idb = false,
	timeout = 9000,
	log_lvl = 0
}: {
	api_cfg: any;
	code: string;
	data_type?: string;
	save_idb?: boolean;
	timeout?: number;
	log_lvl?: number;
}): Promise<any> {
	if (log_lvl) {
		console.log(`*** load_ae_obj_by_code__data_store() *** code=${code}`);
	}

	if (!code) {
		console.log(`*ae_func* No code provided!`);
		return null;
	}

	if (!api_cfg.account_id) {
		console.log(`*ae_func* No account_id found in API config!`);
		return null;
	}

	try {
		const get_ds_result = await api.get_data_store_obj_w_code({
			api_cfg: api_cfg,
			data_store_code: code,
			data_type: data_type,
			timeout: timeout,
			log_lvl: log_lvl
		});

		if (!get_ds_result) {
			console.log('*ae_func* No results returned.');
			return null;
		}

		if (log_lvl) {
			console.log(`*ae_func* Got a result for code ${code}`);
		}

		if (!get_ds_result.data_store_id_random) {
			console.log('*ae_func* Something went wrong? No data store ID found.');
			return null;
		}

		let return_this: any = null;

		// Simplified data extraction
		if (data_type === 'html') {
			return_this = get_ds_result.html;
		} else if (data_type === 'json') {
			return_this = get_ds_result.json;
		} else {
			return_this = get_ds_result.text;
		}

		if (save_idb && browser) {
			const key_prefix = 'ae_ds__';
			if (log_lvl) {
				console.log(`*ae_func* localStorage key: ${code}, value:`, get_ds_result);
			}
			localStorage.setItem(`${key_prefix}${code}`, JSON.stringify(get_ds_result));
		}

		return return_this;
	} catch (error) {
		console.log('*ae_func* No results returned or failed.', error);
		return null;
	}
}
