-- Supabase Database Fixes for Website Monitoring Frontend
-- Run this in your Supabase SQL editor

-- 0. Create missing enum types if they don't exist
DO $$ BEGIN
    CREATE TYPE scan_status AS ENUM (
        'pending',
        'queued',
        'running',
        'completed',
        'failed',
        'cancelled'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
    CREATE TYPE severity_level AS ENUM (
        'critical',
        'high',
        'medium',
        'low',
        'info'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
    CREATE TYPE comparison_operator AS ENUM (
        'less_than',
        'less_than_equal',
        'greater_than',
        'greater_than_equal',
        'equal_to',
        'not_equal_to'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
    CREATE TYPE metric_category AS ENUM (
        'performance',
        'seo',
        'accessibility',
        'best_practices',
        'security',
        'pwa'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
    CREATE TYPE resource_type AS ENUM (
        'script',
        'stylesheet',
        'image',
        'font',
        'document',
        'media',
        'other'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
    CREATE TYPE notification_channel AS ENUM (
        'email',
        'slack',
        'webhook',
        'in_app'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
    CREATE TYPE subscription_tier AS ENUM (
        'free',
        'starter',
        'professional',
        'enterprise'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

DO $$ BEGIN
    CREATE TYPE user_role AS ENUM (
        'owner',
        'admin',
        'editor',
        'viewer'
    );
EXCEPTION
    WHEN duplicate_object THEN null;
END $$;

-- 1. Add missing columns to scans table
ALTER TABLE scans ADD COLUMN IF NOT EXISTS scheduled_at TIMESTAMPTZ;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS trigger_type VARCHAR DEFAULT 'manual';
ALTER TABLE scans ADD COLUMN IF NOT EXISTS website_id UUID REFERENCES websites(id);
ALTER TABLE scans ADD COLUMN IF NOT EXISTS triggered_by UUID REFERENCES users(id);
ALTER TABLE scans ADD COLUMN IF NOT EXISTS scan_type VARCHAR DEFAULT 'full';
ALTER TABLE scans ADD COLUMN IF NOT EXISTS priority INTEGER DEFAULT 1;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS categories TEXT[] DEFAULT ARRAY['performance', 'seo', 'accessibility', 'best_practices'];
ALTER TABLE scans ADD COLUMN IF NOT EXISTS device_type VARCHAR DEFAULT 'desktop';
ALTER TABLE scans ADD COLUMN IF NOT EXISTS user_agent VARCHAR;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS lighthouse_version VARCHAR;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS chrome_version VARCHAR;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS environment JSONB DEFAULT '{}'::jsonb;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS started_at TIMESTAMPTZ DEFAULT NOW();
ALTER TABLE scans ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS duration_ms INTEGER;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS error_message TEXT;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS retry_count INTEGER DEFAULT 0;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT '{}'::jsonb;
ALTER TABLE scans ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ DEFAULT NOW();

-- 2. Add missing columns to scan_results table if they don't exist
ALTER TABLE scan_results ADD COLUMN IF NOT EXISTS raw_data JSONB DEFAULT '{}'::jsonb;

-- 3. Add missing columns to metric_values table if they don't exist
ALTER TABLE metric_values ADD COLUMN IF NOT EXISTS raw_value VARCHAR;
ALTER TABLE metric_values ADD COLUMN IF NOT EXISTS unit VARCHAR;
ALTER TABLE metric_values ADD COLUMN IF NOT EXISTS is_passing BOOLEAN;

-- 4. Add missing columns to resource_analysis table if they don't exist
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS transfer_size_bytes INTEGER;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS duration_ms INTEGER;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS is_third_party BOOLEAN DEFAULT false;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS is_cached BOOLEAN;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS compression_ratio NUMERIC;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS mime_type VARCHAR;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS protocol VARCHAR;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS priority VARCHAR;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS status_code INTEGER;
ALTER TABLE resource_analysis ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT '{}'::jsonb;

-- 5. Add missing columns to alert_configurations table if they don't exist
ALTER TABLE alert_configurations ADD COLUMN IF NOT EXISTS consecutive_count INTEGER DEFAULT 1;
ALTER TABLE alert_configurations ADD COLUMN IF NOT EXISTS cooldown_minutes INTEGER DEFAULT 60;
ALTER TABLE alert_configurations ADD COLUMN IF NOT EXISTS notification_template TEXT;
ALTER TABLE alert_configurations ADD COLUMN IF NOT EXISTS last_triggered_at TIMESTAMPTZ;

-- 6. Add missing columns to alerts table if they don't exist
ALTER TABLE alerts ADD COLUMN IF NOT EXISTS details JSONB DEFAULT '{}'::jsonb;
ALTER TABLE alerts ADD COLUMN IF NOT EXISTS acknowledged_by UUID REFERENCES users(id);
ALTER TABLE alerts ADD COLUMN IF NOT EXISTS acknowledged_at TIMESTAMPTZ;
ALTER TABLE alerts ADD COLUMN IF NOT EXISTS resolved_at TIMESTAMPTZ;

-- 7. Add missing columns to crawl_queue table if they don't exist
ALTER TABLE crawl_queue ADD COLUMN IF NOT EXISTS discovery_depth INTEGER DEFAULT 0;
ALTER TABLE crawl_queue ADD COLUMN IF NOT EXISTS attempts INTEGER DEFAULT 0;
ALTER TABLE crawl_queue ADD COLUMN IF NOT EXISTS parent_url VARCHAR;
ALTER TABLE crawl_queue ADD COLUMN IF NOT EXISTS priority INTEGER DEFAULT 1;
ALTER TABLE crawl_queue ADD COLUMN IF NOT EXISTS error_message TEXT;
ALTER TABLE crawl_queue ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT '{}'::jsonb;

-- 8. Add missing columns to crawl_sessions table if they don't exist
ALTER TABLE crawl_sessions ADD COLUMN IF NOT EXISTS pages_discovered INTEGER DEFAULT 0;
ALTER TABLE crawl_sessions ADD COLUMN IF NOT EXISTS pages_processed INTEGER DEFAULT 0;
ALTER TABLE crawl_sessions ADD COLUMN IF NOT EXISTS current_url VARCHAR;
ALTER TABLE crawl_sessions ADD COLUMN IF NOT EXISTS error_message TEXT;
ALTER TABLE crawl_sessions ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT '{}'::jsonb;

-- 9. Create indexes if they don't exist
CREATE INDEX IF NOT EXISTS idx_scans_scheduled_at ON scans(scheduled_at);
CREATE INDEX IF NOT EXISTS idx_scan_results_category ON scan_results(category);
CREATE INDEX IF NOT EXISTS idx_metric_values_created_at ON metric_values(created_at);
CREATE INDEX IF NOT EXISTS idx_resource_analysis_type ON resource_analysis(resource_type);
CREATE INDEX IF NOT EXISTS idx_alerts_status ON alerts(status);
CREATE INDEX IF NOT EXISTS idx_crawl_queue_status_priority ON crawl_queue(status, priority);
CREATE INDEX IF NOT EXISTS idx_crawl_sessions_status ON crawl_sessions(status);

-- 10. Add RLS policies if they don't exist (basic ones)
-- Note: You may need to customize these based on your security requirements

-- Enable RLS on all tables
ALTER TABLE scans ENABLE ROW LEVEL SECURITY;
ALTER TABLE scan_results ENABLE ROW LEVEL SECURITY;
ALTER TABLE metric_values ENABLE ROW LEVEL SECURITY;
ALTER TABLE resource_analysis ENABLE ROW LEVEL SECURITY;
ALTER TABLE alert_configurations ENABLE ROW LEVEL SECURITY;
ALTER TABLE alerts ENABLE ROW LEVEL SECURITY;
ALTER TABLE crawl_queue ENABLE ROW LEVEL SECURITY;
ALTER TABLE crawl_sessions ENABLE ROW LEVEL SECURITY;

-- Basic RLS policies (you may want to customize these)
CREATE POLICY IF NOT EXISTS "Users can view scans for their organization" ON scans
    FOR SELECT USING (
        website_id IN (
            SELECT id FROM websites WHERE organization_id IN (
                SELECT organization_id FROM users WHERE id = auth.uid()
            )
        )
    );

CREATE POLICY IF NOT EXISTS "Users can insert scans for their organization" ON scans
    FOR INSERT WITH CHECK (
        website_id IN (
            SELECT id FROM websites WHERE organization_id IN (
                SELECT organization_id FROM users WHERE id = auth.uid()
            )
        )
    );

CREATE POLICY IF NOT EXISTS "Users can update scans for their organization" ON scans
    FOR UPDATE USING (
        website_id IN (
            SELECT id FROM websites WHERE organization_id IN (
                SELECT organization_id FROM users WHERE id = auth.uid()
            )
        )
    );

-- Similar policies for other tables...
-- (You may want to add more comprehensive RLS policies based on your needs)

-- 11. Refresh Supabase schema cache to pick up new columns
-- This is important to resolve "Could not find column in schema cache" errors
NOTIFY pgrst, 'reload schema';

COMMIT; 