import { writable } from 'svelte/store';
import { api } from '$lib/api/client';

export interface Alliance {
	id: number;
	name: string;
	description: string | null;
	hqLatitude: number | null;
	hqLongitude: number | null;
	pixelsPainted: number;
}

function createAllianceStore() {
	const { subscribe, set, update } = writable<Alliance | null>(null);

	return {
		subscribe,
		set,
		update,
		async fetch() {
			try {
				const alliance = await api.getAlliance();
				set(alliance);
				return alliance;
			} catch (error) {
				console.error('Failed to fetch alliance:', error);
				set(null);
				return null;
			}
		},
		async create(name: string) {
			try {
				const alliance = await api.createAlliance(name);
				set(alliance);
				return alliance;
			} catch (error) {
				console.error('Failed to create alliance:', error);
				throw error;
			}
		},
		async updateDescription(description: string) {
			try {
				const alliance = await api.updateAllianceDescription(description);
				set(alliance);
				return alliance;
			} catch (error) {
				console.error('Failed to update description:', error);
				throw error;
			}
		},
		async updateHeadquarters(lat: number, lng: number) {
			try {
				const alliance = await api.updateAllianceHeadquarters(lat, lng);
				set(alliance);
				return alliance;
			} catch (error) {
				console.error('Failed to update headquarters:', error);
				throw error;
			}
		},
		clear() {
			set(null);
		}
	};
}

export const currentAlliance = createAllianceStore();
