CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_desktop_tasks_monitor_queue_account_order
    ON desktop_tasks (
        tenant_id,
        workspace_id,
        target_account_id,
        platform_id,
        lane_weight DESC,
        priority DESC,
        enqueued_at ASC,
        created_at ASC,
        desktop_id ASC
    )
    WHERE kind = 'monitor'
      AND status = 'queued';

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_desktop_tasks_monitor_active_platform_account
    ON desktop_tasks (
        tenant_id,
        workspace_id,
        platform_id,
        status,
        target_account_id,
        updated_at DESC
    )
    WHERE kind = 'monitor'
      AND status IN ('in_progress', 'succeeded', 'failed', 'unknown', 'aborted');

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_desktop_tasks_monitor_active_client_platform
    ON desktop_tasks (
        tenant_id,
        workspace_id,
        target_client_id,
        platform_id,
        status,
        desktop_id
    )
    WHERE kind = 'monitor'
      AND status = 'in_progress';

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_platform_accounts_monitor_identity_fingerprint
    ON platform_accounts (
        tenant_id,
        workspace_id,
        user_id,
        platform_id,
        account_fingerprint
    )
    WHERE deleted_at IS NULL
      AND delete_requested_at IS NULL
      AND btrim(COALESCE(account_fingerprint, '')) <> '';

CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_platform_accounts_monitor_identity_uid
    ON platform_accounts (
        tenant_id,
        workspace_id,
        user_id,
        platform_id,
        platform_uid
    )
    WHERE deleted_at IS NULL
      AND delete_requested_at IS NULL
      AND btrim(COALESCE(platform_uid, '')) <> '';
