-- EXISTING databases only: apply once with discovery and tag administration stopped.
-- Fresh installations use 040 (already includes these columns), then 041.
-- MariaDB DDL commits implicitly. Back up the table before applying this migration.
-- Do not apply 040 again to an existing database.
ALTER TABLE finops_tag_key
    ADD COLUMN nature ENUM('BUSINESS','TECHNICAL','SYSTEM') NULL,
    ADD COLUMN functional_type VARCHAR(255) NULL,
    ADD COLUMN processing_policy ENUM('NORMALIZE','ANALYZE','DISCOVER_ONLY','IGNORE')
        NOT NULL DEFAULT 'DISCOVER_ONLY',
    ADD KEY idx_tag_key_governance (nature, processing_policy, first_seen_date);

-- Preserve all existing canonical pointers and the legacy classification.
-- An ignored key stays ignored, even if it has a stored mapping.
-- Otherwise a mapped key keeps NORMALIZE, including technical/unqualified keys.
UPDATE finops_tag_key
SET nature = CASE WHEN classification IN ('BUSINESS', 'TECHNICAL')
                  THEN classification ELSE NULL END,
    processing_policy = CASE
        WHEN classification = 'IGNORED' THEN 'IGNORE'
        WHEN canonical_key_id IS NOT NULL OR classification = 'BUSINESS' THEN 'NORMALIZE'
        WHEN classification = 'TECHNICAL' THEN 'ANALYZE'
        ELSE 'DISCOVER_ONLY'
    END;

-- Next, reapply 041_create_tag_governance_views.sql, then deploy the new
-- application and batch together. No discovery/backfill replay is required.
-- Do not run the old administration API concurrently: it only knows classification.
