import { getGoogleAccessToken, googleFetch } from './google-auth.js';

function shapeListEvent(event = {}) {
  return {
    id: event.id,
    summary: event.summary || '',
    start: event.start || null,
    end: event.end || null,
    attendees: event.attendees || [],
    status: event.status || null,
    html_link: event.htmlLink || null,
  };
}

function shapeFullEvent(event = {}) {
  return {
    ...shapeListEvent(event),
    description: event.description || '',
    location: event.location || '',
    creator: event.creator || null,
    organizer: event.organizer || null,
    recurrence: event.recurrence || [],
    conference_data: event.conferenceData || null,
  };
}

async function fetchCalendarJson(url, token, opts, toolName) {
  const loggedFetch = googleFetch(toolName, opts);
  const res = await loggedFetch(url, { headers: { Authorization: `Bearer ${token}` } });
  if (!res.ok) throw new Error(`google calendar failed: ${res.status}`);
  return res.json();
}

export async function calendar_events_list(args = {}, opts = {}) {
  const toolName = 'calendar_events_list';
  const token = await getGoogleAccessToken(opts, toolName);
  const calendarId = encodeURIComponent(args.calendar_id || 'primary');
  const url = new URL(`https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events`);
  if (args.time_min) url.searchParams.set('timeMin', args.time_min);
  if (args.time_max) url.searchParams.set('timeMax', args.time_max);
  if (args.max_results) url.searchParams.set('maxResults', String(args.max_results));
  const data = await fetchCalendarJson(url, token, opts, toolName);
  return (data.items || []).map(shapeListEvent);
}

export async function calendar_event_read(args = {}, opts = {}) {
  if (!args.event_id) throw new Error('event_id is required');
  const toolName = 'calendar_event_read';
  const token = await getGoogleAccessToken(opts, toolName);
  const calendarId = encodeURIComponent(args.calendar_id || 'primary');
  const eventId = encodeURIComponent(args.event_id);
  const data = await fetchCalendarJson(`https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events/${eventId}`, token, opts, toolName);
  return shapeFullEvent(data);
}
