import { System } from '@/lib/types';
import pb from '@/lib/pocketbase';

const wormholeCollection = pb.collection('wormholeSystems');

// Load all wormhole systems
export const loadWormholeSystems = async (): Promise<Map<string, System>> => {
	try {
		const systems = await wormholeCollection.getFullList<System>();
		return new Map(systems.map(system => [system.solarSystemName, system]));
	} catch (error) {
		console.error('Error loading wormhole systems:', error);
		return new Map();
	}
};

// Save/update a wormhole system
export const saveWormholeSystem = async (system: System): Promise<System> => {
	try {
		console.log('Saving wormhole system:', system);
		if (system.id) {
			return await wormholeCollection.update(system.id, system);
		} else {
			return await wormholeCollection.create(system);
		}
	} catch (error) {
		console.error('Error saving wormhole system:', error);
		throw error;
	}
};

export const deleteWormholeSystem = async (system: System): Promise<void> => {
	try {
		if (!system.id) {
			throw new Error('System has no ID');
		}
		await wormholeCollection.delete(system.id);
	} catch (error) {
		console.error('Error deleting wormhole system:', error);
		throw error;
	}
};
