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

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

// 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) {
			await wormholeCollection.update(system.id, system);
			const legitSystem: SystemRecord = {
				id: system.id,
				name: system.solarSystemName,
				region: "Wormhole",
				connectedTo: system.connectedSystems
			}
			await systemsCollection.update(system.id, legitSystem);
		} else {
			const createdWormhole = await wormholeCollection.create(system);
			const legitSystem: SystemRecord = {
				id: createdWormhole.id,
				name: createdWormhole.solarSystemName,
				region: "Wormhole",
				connectedTo: createdWormhole.connectedSystems,
			}
			await systemsCollection.create(legitSystem);
			return createdWormhole;
		}
	} 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);
		await systemsCollection.delete(system.id);
	} catch (error) {
		console.error('Error deleting wormhole system:', error);
		throw error;
	}
};
