-- Migration to remove query functionality from the database
-- This drops all query-related tables, views, and functions

-- First drop the function that depends on query views
DROP FUNCTION IF EXISTS collectorQueryDependencyTreeByClient;

-- Drop the collector views that depend on query tables (in order of dependencies)
DROP VIEW IF EXISTS collectorQueryDependencyTree;
DROP VIEW IF EXISTS fullActiveCollectors;
DROP VIEW IF EXISTS currentCollectorQueriesJSONAGG;
DROP VIEW IF EXISTS currentCollectorQueries;

-- Drop query views (in order of dependencies)
DROP VIEW IF EXISTS fullActiveQueries;
DROP VIEW IF EXISTS queryActiveDependencies;
DROP VIEW IF EXISTS queryCurrentRequiredIdsAGG;
DROP VIEW IF EXISTS queryCurrentRequiredIds;
DROP VIEW IF EXISTS queryCurrentConfigs;
DROP VIEW IF EXISTS queryLatestVersions;
DROP VIEW IF EXISTS queryCurrentActiveVersions;

-- Drop result tables
DROP TABLE IF EXISTS resultDependencies;
DROP TABLE IF EXISTS results;

-- Drop collectorQueries table (links collectors to queries)
DROP TABLE IF EXISTS collectorQueries;

-- Drop query configuration and dependency tables
DROP TABLE IF EXISTS queryConfigs;
DROP TABLE IF EXISTS requiredQueries;
DROP TABLE IF EXISTS queryActiveVersions;
DROP TABLE IF EXISTS queryVersions;
DROP TABLE IF EXISTS queries;

-- Drop triggers and functions
DROP TRIGGER IF EXISTS setQueryVersionNumberTrigger ON queryVersions;
DROP FUNCTION IF EXISTS setQueryVersionNumber;
DROP TRIGGER IF EXISTS removeQueryConfigTrigger ON queryConfigs;
DROP FUNCTION IF EXISTS removeQueryConfig;

-- Drop the query type enum
DROP TYPE IF EXISTS queryType;

-- Recreate the fullActiveCollectors view without the fields column
CREATE VIEW fullActiveCollectors AS
    SELECT DISTINCT av.clientId,
    ccv.minCleanVersion, ctv.minTextVersion,
    av.activeVersion, lv.latestVersion
    FROM collectorCurrentActiveVersions as av
    JOIN collectorLatestVersions as lv on lv.clientId = av.clientId
    JOIN currentCollectorMinCleanVersions AS ccv ON av.clientId = ccv.clientId
    JOIN currentCollectorMinTextVersions AS ctv ON av.clientId = ctv.clientId;
