\pset border 2
\pset format aligned

\echo '== A. Calendar event coverage on active tasks (last 30 days + future) =='
SELECT
  COALESCE(NULLIF(x_fc_sync_source,''), '<local>') AS source,
  status,
  COUNT(*) AS task_count,
  COUNT(calendar_event_id) AS with_calendar_event,
  COUNT(*) - COUNT(calendar_event_id) AS missing
FROM fusion_technician_task
WHERE active = TRUE
  AND scheduled_date >= CURRENT_DATE - 30
  AND technician_id IS NOT NULL
GROUP BY 1, 2
ORDER BY 1, 2;

\echo ''
\echo '== B. Spot-check: recent tasks WITHOUT calendar_event_id =='
SELECT id, name, technician_id, x_fc_sync_source, status, scheduled_date, datetime_start, datetime_end
FROM fusion_technician_task
WHERE active = TRUE
  AND scheduled_date >= CURRENT_DATE - 7
  AND technician_id IS NOT NULL
  AND calendar_event_id IS NULL
  AND status NOT IN ('cancelled', 'completed')
ORDER BY scheduled_date DESC, id DESC
LIMIT 20;

\echo ''
\echo '== C. Sample of linked calendar.event records (most recent 5) =='
SELECT t.id AS task_id, t.name AS task_name,
       ce.id AS event_id, ce.name AS event_name,
       ce.start AS ev_start, ce.stop AS ev_stop,
       t.x_fc_sync_source AS source
FROM fusion_technician_task t
JOIN calendar_event ce ON ce.id = t.calendar_event_id
WHERE t.active = TRUE
ORDER BY t.write_date DESC
LIMIT 5;

\echo ''
\echo '== D. Are external calendar sync modules installed? =='
SELECT name, state, latest_version FROM ir_module_module
WHERE name IN ('google_calendar', 'microsoft_calendar', 'calendar', 'mail')
   OR name LIKE '%calendar%'
ORDER BY name;
