import type { Pool } from 'pg';
import { pgAll, pgRun } from '@/shared/db';
import type { CalendarDraft, CalendarRecord } from './types';

interface Row {
  id: string;
  device_id: string;
  external_id: string;
  title: string;
  calendar_type: string;
  color: string;
  source: string;
  synced_at: string;
}

const hydrate = (r: Row): CalendarRecord => ({
  id: r.id,
  deviceId: r.device_id,
  externalId: r.external_id,
  title: r.title,
  calendarType: r.calendar_type,
  color: r.color,
  source: r.source,
  syncedAt: r.synced_at,
});

export async function upsertCalendar(pool: Pool, draft: CalendarDraft): Promise<void> {
  await pgRun(
    pool,
    `INSERT INTO macsync.calendars (id, device_id, external_id, title, calendar_type, color, source)
     VALUES ($1, $2, $3, $4, $5, $6, $7)
     ON CONFLICT(device_id, external_id) DO UPDATE SET
       title = excluded.title,
       calendar_type = excluded.calendar_type,
       color = excluded.color,
       source = excluded.source,
       synced_at = now()`,
    [draft.id, draft.deviceId, draft.externalId, draft.title, draft.calendarType, draft.color, draft.source],
  );
}

export async function listCalendarsByDevice(pool: Pool, deviceId: string): Promise<readonly CalendarRecord[]> {
  const rows = await pgAll<Row>(pool, 'SELECT * FROM macsync.calendars WHERE device_id = $1 ORDER BY title ASC', [deviceId]);
  return rows.map(hydrate);
}

export async function countCalendars(pool: Pool): Promise<number> {
  const row = await pgAll<{ n: number }>(pool, 'SELECT COUNT(*) as n FROM macsync.calendars');
  return row[0]?.n ?? 0;
}
