\pset border 2
\pset format aligned

\echo '== 1. Local instance ID =='
SELECT key, value
FROM ir_config_parameter
WHERE key = 'fusion_claims.sync_instance_id';

\echo ''
\echo '== 2. Remote sync configs (other instances we sync with) =='
SELECT id, name, instance_id, url, database, username, active,
       last_sync, LEFT(COALESCE(last_sync_error,''), 200) AS last_sync_error
FROM fusion_task_sync_config;

\echo ''
\echo '== 3. Field technicians and sync IDs =='
SELECT u.id, u.login, p.name AS partner_name,
       u.x_fc_is_field_staff, u.x_fc_tech_sync_id, u.active
FROM res_users u
JOIN res_partner p ON p.id = u.partner_id
WHERE u.x_fc_is_field_staff = TRUE
   OR (u.x_fc_tech_sync_id IS NOT NULL AND u.x_fc_tech_sync_id <> '')
ORDER BY u.active DESC, u.login;

\echo ''
\echo '== 4. Recent task flow (last 7 days) =='
SELECT
  COALESCE(NULLIF(x_fc_sync_source,''), '<local>') AS source,
  status,
  COUNT(*) AS cnt,
  MIN(scheduled_date) AS min_date,
  MAX(scheduled_date) AS max_date
FROM fusion_technician_task
WHERE create_date > NOW() - INTERVAL '7 days'
GROUP BY 1, 2
ORDER BY 1, 2;

\echo ''
\echo '== 5. Cron jobs for Fusion Tasks =='
SELECT
  c.id,
  REPLACE(REPLACE(c.cron_name, 'Fusion Tasks:', ''), '  ', ' ') AS job,
  c.active,
  c.interval_number || ' ' || c.interval_type AS every,
  c.lastcall, c.nextcall
FROM ir_cron c
WHERE c.cron_name LIKE 'Fusion Tasks%'
ORDER BY c.cron_name;

\echo ''
\echo '== 6. Tasks scheduled today/tomorrow by tech =='
SELECT
  u.login AS tech_login,
  u.x_fc_tech_sync_id AS sync_id,
  COALESCE(NULLIF(t.x_fc_sync_source,''), '<local>') AS source,
  COUNT(*) AS cnt
FROM fusion_technician_task t
JOIN res_users u ON u.id = t.technician_id
WHERE t.scheduled_date BETWEEN CURRENT_DATE - 1 AND CURRENT_DATE + 7
  AND t.active = TRUE
GROUP BY 1,2,3
ORDER BY 1,3;
