import { browser } from '$app/environment';

export const CSV_IMPORT_SESSION_KEY = 'anexo76_csv_import_v1';

export const CSV_IMPORT_SESSION_CHANGED = 'csvImportSessionChanged';

/** Debe coincidir con la cadena de `pollStatus` en csv-upload/+page.svelte */
export type CsvImportProfile =
	| 'customs_brokers'
	| 'clients_providers'
	| 'exchange_rates'
	| 'pedimentos'
	| 'material_classes'
	| 'vehicles'
	| 'drivers'
	| 'trailers'
	| 'transporters'
	| 'part_numbers'
	| 'boms'
	| 'exportacion'
	| 'imports';

export type CsvImportTab = 'catalogos' | 'transportes' | 'importacion' | 'exportacion';

export interface CsvImportSessionV1 {
	v: 1;
	companyId: number;
	jobId: string;
	profile: CsvImportProfile;
	activeModelTarget: string | null;
	activeTab: CsvImportTab;
	/** Título del ítem de carga (p. ej. nombre del catálogo) para banner / contexto */
	label?: string | null;
}

function notifySessionChanged() {
	if (browser) {
		window.dispatchEvent(new CustomEvent(CSV_IMPORT_SESSION_CHANGED));
	}
}

export function readCsvImportSession(activeCompanyId: number | undefined): CsvImportSessionV1 | null {
	if (!browser || activeCompanyId === undefined) return null;
	try {
		const raw = sessionStorage.getItem(CSV_IMPORT_SESSION_KEY);
		if (!raw) return null;
		const data = JSON.parse(raw) as Partial<CsvImportSessionV1>;
		if (data.v !== 1 || typeof data.jobId !== 'string' || typeof data.companyId !== 'number') {
			return null;
		}
		if (data.companyId !== activeCompanyId) return null;
		if (!isCsvImportProfile(data.profile)) return null;
		if (!isCsvImportTab(data.activeTab)) return null;
		const label =
			data.label === null || data.label === undefined
				? undefined
				: typeof data.label === 'string'
					? data.label
					: undefined;
		return {
			v: 1,
			companyId: data.companyId,
			jobId: data.jobId,
			profile: data.profile,
			activeModelTarget:
				data.activeModelTarget === null || data.activeModelTarget === undefined
					? null
					: typeof data.activeModelTarget === 'string'
						? data.activeModelTarget
						: null,
			activeTab: data.activeTab,
			...(label !== undefined ? { label } : {})
		};
	} catch {
		return null;
	}
}

export function hasCsvImportSessionForCompany(activeCompanyId: number | undefined): boolean {
	return readCsvImportSession(activeCompanyId) !== null;
}

function isCsvImportProfile(p: unknown): p is CsvImportProfile {
	return (
		typeof p === 'string' &&
		[
			'customs_brokers',
			'clients_providers',
			'exchange_rates',
			'pedimentos',
			'material_classes',
			'vehicles',
			'drivers',
			'trailers',
			'transporters',
			'part_numbers',
			'boms',
			'exportacion',
			'imports'
		].includes(p)
	);
}

function isCsvImportTab(t: unknown): t is CsvImportTab {
	return (
		typeof t === 'string' &&
		['catalogos', 'transportes', 'importacion', 'exportacion'].includes(t)
	);
}

export function saveCsvImportSession(session: CsvImportSessionV1): void {
	if (!browser) return;
	try {
		sessionStorage.setItem(CSV_IMPORT_SESSION_KEY, JSON.stringify(session));
		notifySessionChanged();
	} catch {
		// quota / private mode
	}
}

export function clearCsvImportSession(): void {
	if (!browser) return;
	try {
		sessionStorage.removeItem(CSV_IMPORT_SESSION_KEY);
		notifySessionChanged();
	} catch {
		//
	}
}
