import { _getAccessToken, _isAuthorized, _authorize } from "./oauth.js";
const CALENDAR_API = "https://www.googleapis.com/calendar/v3";
const PROVIDER_NAME = "google-calendar";
const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
const TOKEN_URL = "https://oauth2.googleapis.com/token";
const SCOPES = "https://www.googleapis.com/auth/calendar";
async function getToken() {
    return _getAccessToken(PROVIDER_NAME);
}
function parseEventTime(dt) {
    return dt.dateTime || dt.date || "";
}
function formatEvent(raw) {
    return {
        id: raw.id || "",
        summary: raw.summary || "",
        description: raw.description || "",
        location: raw.location || "",
        start: parseEventTime(raw.start || {}),
        end: parseEventTime(raw.end || {}),
        htmlLink: raw.htmlLink || "",
    };
}
function buildEventTime(datetime) {
    // If it looks like a date-only string (YYYY-MM-DD), use date field
    if (/^\d{4}-\d{2}-\d{2}$/.test(datetime)) {
        return { date: datetime };
    }
    return { dateTime: datetime };
}
export async function _authorizeCalendar(clientId, clientSecret) {
    return _authorize(PROVIDER_NAME, {
        authUrl: AUTH_URL,
        tokenUrl: TOKEN_URL,
        clientId,
        clientSecret,
        scopes: SCOPES,
        extraAuthParams: { access_type: "offline", prompt: "consent" },
    });
}
export async function _listEvents(params) {
    const token = await getToken();
    const calendarId = params?.calendarId || "primary";
    const url = new URL(`${CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events`);
    url.searchParams.set("singleEvents", "true");
    url.searchParams.set("orderBy", "startTime");
    if (params?.maxResults)
        url.searchParams.set("maxResults", String(params.maxResults));
    if (params?.timeMin)
        url.searchParams.set("timeMin", params.timeMin);
    if (params?.timeMax)
        url.searchParams.set("timeMax", params.timeMax);
    if (params?.query)
        url.searchParams.set("q", params.query);
    if (!params?.timeMin) {
        url.searchParams.set("timeMin", new Date().toISOString());
    }
    if (!params?.maxResults) {
        url.searchParams.set("maxResults", "10");
    }
    const response = await fetch(url.toString(), {
        headers: { "Authorization": `Bearer ${token}` },
    });
    if (!response.ok) {
        const errBody = await response.text();
        throw new Error(`Google Calendar API error (${response.status}): ${errBody.slice(0, 200)}`);
    }
    const data = await response.json();
    return (data.items || []).map(formatEvent);
}
export async function _createEvent(params) {
    const token = await getToken();
    const calendarId = params.calendarId || "primary";
    const body = {
        summary: params.summary,
        start: buildEventTime(params.start),
        end: buildEventTime(params.end),
    };
    if (params.description)
        body.description = params.description;
    if (params.location)
        body.location = params.location;
    if (params.attendees) {
        body.attendees = params.attendees.map((email) => ({ email }));
    }
    const response = await fetch(`${CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events`, {
        method: "POST",
        headers: {
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify(body),
    });
    if (!response.ok) {
        const responseBody = await response.text();
        throw new Error(`Google Calendar API error (${response.status}): ${responseBody.slice(0, 200)}`);
    }
    const data = await response.json();
    return formatEvent(data);
}
export async function _updateEvent(params) {
    const token = await getToken();
    const calendarId = params.calendarId || "primary";
    const body = {};
    if (params.summary)
        body.summary = params.summary;
    if (params.start)
        body.start = buildEventTime(params.start);
    if (params.end)
        body.end = buildEventTime(params.end);
    if (params.description)
        body.description = params.description;
    if (params.location)
        body.location = params.location;
    const response = await fetch(`${CALENDAR_API}/calendars/${encodeURIComponent(calendarId)}/events/${encodeURIComponent(params.eventId)}`, {
        method: "PATCH",
        headers: {
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify(body),
    });
    if (!response.ok) {
        const responseBody = await response.text();
        throw new Error(`Google Calendar API error (${response.status}): ${responseBody.slice(0, 200)}`);
    }
    const data = await response.json();
    return formatEvent(data);
}
export async function _deleteEvent(eventId, calendarId) {
    const token = await getToken();
    const cal = calendarId || "primary";
    const response = await fetch(`${CALENDAR_API}/calendars/${encodeURIComponent(cal)}/events/${encodeURIComponent(eventId)}`, {
        method: "DELETE",
        headers: { "Authorization": `Bearer ${token}` },
    });
    if (!response.ok && response.status !== 410) {
        const responseBody = await response.text();
        throw new Error(`Google Calendar API error (${response.status}): ${responseBody.slice(0, 200)}`);
    }
    return { deleted: true };
}
export async function _isCalendarAuthorized() {
    return _isAuthorized(PROVIDER_NAME);
}
