import { invoke } from "@tauri-apps/api/core";

export type AuthScheme = "Digest" | "Basic";

export interface DAVCredentials {
	scheme: AuthScheme;
	username: string;
	password: string;
}

export interface DAVCalendar {
	name: string;
	url: string;
}

export interface DAVEvent {
	summary: string;
	start?: Date;
	end?: Date;
	description?: string;
	location?: string;
}

export async function findScheme(url: string): Promise<AuthScheme> {
	const scheme = await invoke("dav_find_scheme", { url });
	return scheme as AuthScheme;
}

export async function fetchCalendars(
	url: string,
	credentials: DAVCredentials,
): Promise<DAVCalendar[]> {
	const calendars = await invoke("dav_fetch_calendars", { url, credentials });
	return calendars as DAVCalendar[];
}

export async function fetchEvents(
	calendar: DAVCalendar,
	credentials: DAVCredentials,
): Promise<DAVEvent[]> {
	const events = await invoke("dav_fetch_events", { calendar, credentials });
	return (events as DAVEvent[]).map((e) => {
		if (e.start) e.start = new Date(e.start);
		if (e.end) e.end = new Date(e.end);
		return e;
	}) as DAVEvent[];
}
