-- Rollback T24: revoke auto_repair_executor Docker restart write grant.

SELECT set_config('app.project_id', 'awoooi', FALSE);

UPDATE awooop_mcp_grants
SET is_revoked = TRUE,
    revoked_at = NOW(),
    revoked_by = 'rollback:t24_auto_repair_docker_restart_gateway'
WHERE project_id = 'awoooi'
  AND agent_id = 'auto_repair_executor'
  AND granted_by = 'migration:t24_auto_repair_docker_restart_gateway';

WITH previous_revision AS (
    SELECT revision_id, project_id, contract_family, contract_id
    FROM awooop_contract_revisions
    WHERE project_id = 'awoooi'
      AND contract_family = 'agent'
      AND contract_id = 'auto_repair_executor'
      AND version_major = 1
      AND version_minor = 0
      AND lifecycle_status = 'active'
    ORDER BY revision_id DESC
    LIMIT 1
)
INSERT INTO awooop_active_revisions (
    project_id,
    contract_family,
    contract_id,
    active_revision_id,
    updated_at
)
SELECT project_id, contract_family, contract_id, revision_id, NOW()
FROM previous_revision
ON CONFLICT (project_id, contract_family, contract_id)
DO UPDATE SET
    active_revision_id = EXCLUDED.active_revision_id,
    updated_at = NOW();
