-- Seed widgets into existing role_sidebar_configs for EXTERNAL roles
-- This ensures the widget-based dashboard renders correctly for all roles.
--
-- Run this AFTER migrations are applied:
--   psql $DATABASE_URL -f crates/db/migrations/YYYYMMDDTTTTTT_add_widgets_to_sidebar_configs.seed.sql

-- Update COMPANY roles
UPDATE role_sidebar_configs
SET config_json = jsonb_set(
    COALESCE(config_json, '{}'::jsonb),
    '{widgets}',
    '["total_jobs", "active_jobs", "pending_jobs", "applications_received", "shortlisted_candidates", "credits"]'::jsonb,
    true
)
WHERE audience = 'EXTERNAL'
  AND is_active = true
  AND EXISTS (
    SELECT 1 FROM roles r WHERE r.id = role_sidebar_configs.role_id AND r.key = 'COMPANY'
  );

-- Update JOB_SEEKER roles
UPDATE role_sidebar_configs
SET config_json = jsonb_set(
    COALESCE(config_json, '{}'::jsonb),
    '{widgets}',
    '["available_jobs", "my_applications", "shortlisted", "saved_jobs", "profile_status", "verification_status", "portfolio"]'::jsonb,
    true
)
WHERE audience = 'EXTERNAL'
  AND is_active = true
  AND EXISTS (
    SELECT 1 FROM roles r WHERE r.id = role_sidebar_configs.role_id AND r.key = 'JOB_SEEKER'
  );

-- Update CUSTOMER roles
UPDATE role_sidebar_configs
SET config_json = jsonb_set(
    COALESCE(config_json, '{}'::jsonb),
    '{widgets}',
    '["total_requirements", "open_requirements", "closed_requirements", "responses_received", "shortlisted_responses", "credits"]'::jsonb,
    true
)
WHERE audience = 'EXTERNAL'
  AND is_active = true
  AND EXISTS (
    SELECT 1 FROM roles r WHERE r.id = role_sidebar_configs.role_id AND r.key = 'CUSTOMER'
  );

-- Update all remaining EXTERNAL roles (PROFESSIONAL: photographer, makeup, tutor, etc.)
UPDATE role_sidebar_configs
SET config_json = jsonb_set(
    COALESCE(config_json, '{}'::jsonb),
    '{widgets}',
    '["open_leads", "my_requests", "accepted_requests", "tracecoins", "portfolio", "profile_status"]'::jsonb,
    true
)
WHERE audience = 'EXTERNAL'
  AND is_active = true
  AND NOT EXISTS (
    SELECT 1 FROM roles r WHERE r.id = role_sidebar_configs.role_id AND r.key IN ('COMPANY', 'JOB_SEEKER', 'CUSTOMER')
  );

-- Also seed widgets in role_runtime_configs if they differ from role_sidebar_configs
-- (some setups read widgets from runtime_configs)
UPDATE role_runtime_configs
SET config_json = jsonb_set(
    COALESCE(config_json, '{}'::jsonb),
    '{widgets}',
    COALESCE(
      (
        SELECT config_json->'widgets'
        FROM role_sidebar_configs sc
        WHERE sc.role_id = role_runtime_configs.role_id
          AND sc.audience = 'EXTERNAL'
          AND sc.is_active = true
        LIMIT 1
      ),
      '["open_leads", "my_requests", "accepted_requests", "tracecoins", "portfolio", "profile_status"]'::jsonb
    ),
    true
)
WHERE is_active = true;

SELECT 'Widget seed completed.' AS status;
