\pset border 2
\pset format aligned

\echo '== E. Are calendar events linked to the tech as organizer + attendee? =='
SELECT t.id AS task_id, t.name AS task_name,
       ce.user_id AS event_organizer_uid,
       u_org.login AS organizer_login,
       u_tech.login AS task_tech_login,
       (SELECT COUNT(*) FROM calendar_event_res_partner_rel
        WHERE calendar_event_id = ce.id) AS attendee_count,
       (SELECT COUNT(*) FROM calendar_event_res_partner_rel cer
        JOIN res_users u2 ON u2.partner_id = cer.res_partner_id
        WHERE cer.calendar_event_id = ce.id AND u2.id = t.technician_id) AS tech_is_attendee
FROM fusion_technician_task t
JOIN calendar_event ce ON ce.id = t.calendar_event_id
JOIN res_users u_tech ON u_tech.id = t.technician_id
LEFT JOIN res_users u_org ON u_org.id = ce.user_id
WHERE t.active = TRUE
  AND t.scheduled_date >= CURRENT_DATE - 3
  AND t.scheduled_date <= CURRENT_DATE + 7
ORDER BY t.scheduled_date, t.id
LIMIT 12;

\echo ''
\echo '== F. Microsoft Calendar OAuth: how many users have it connected? =='
SELECT
  COUNT(*) FILTER (WHERE microsoft_calendar_token IS NOT NULL AND microsoft_calendar_token <> '') AS users_with_ms_token,
  COUNT(*) FILTER (WHERE x_fc_is_field_staff = TRUE
                     AND microsoft_calendar_token IS NOT NULL
                     AND microsoft_calendar_token <> '') AS field_staff_with_ms_token,
  COUNT(*) FILTER (WHERE x_fc_is_field_staff = TRUE AND active = TRUE) AS active_field_staff
FROM res_users;

\echo ''
\echo '== G. Per-tech: connected to MS calendar? =='
SELECT u.login, u.x_fc_tech_sync_id,
       (microsoft_calendar_token IS NOT NULL AND microsoft_calendar_token <> '') AS ms_connected,
       (microsoft_calendar_sync_token IS NOT NULL AND microsoft_calendar_sync_token <> '') AS ms_sync_token,
       microsoft_calendar_account_id
FROM res_users u
WHERE u.x_fc_is_field_staff = TRUE AND u.active = TRUE
ORDER BY u.login;
