-- Add standard_name column to event_types table
-- This column should not be modifiable by authenticated users

-- Add the standard_name column
ALTER TABLE event_types ADD COLUMN standard_name TEXT;

-- Add comment for the new column
COMMENT ON COLUMN event_types.standard_name IS 
    'Standard name for the event type - not modifiable by authenticated users';

-- Create function to automatically set standard_name on insert and prevent modification by authenticated users
CREATE OR REPLACE FUNCTION handle_event_types_standard_name()
RETURNS TRIGGER AS $$
BEGIN
    -- On INSERT: automatically set standard_name from config->>'name', sanitized
    IF TG_OP = 'INSERT' THEN
        -- Extract name from config and sanitize it (replace spaces with hyphens, lowercase)
        NEW.standard_name = LOWER(REPLACE(TRIM(NEW.config->>'name'), ' ', '-'));
        RETURN NEW;
    END IF;
    
    -- On UPDATE: prevent standard_name modification by authenticated users
    IF TG_OP = 'UPDATE' THEN
        -- Only allow system/service role to modify standard_name
        -- If the current user is authenticated (not service_role), prevent standard_name changes
        IF current_setting('role') != 'service_role' AND OLD.standard_name IS DISTINCT FROM NEW.standard_name THEN RAISE EXCEPTION 'standard_name column cannot be modified'; END IF;
        
        -- If name in config changes, update standard_name accordingly (but only for non-authenticated users)
        IF current_setting('role') = 'service_role' AND OLD.config->>'name' IS DISTINCT FROM NEW.config->>'name' THEN
            NEW.standard_name = LOWER(REPLACE(TRIM(NEW.config->>'name'), ' ', '-'));
        END IF;
    END IF;
    
    RETURN NEW;
END;
$$ language 'plpgsql';

-- Create trigger to handle standard_name on insert and prevent modification on update
CREATE TRIGGER handle_event_types_standard_name_trigger
    BEFORE INSERT OR UPDATE ON event_types
    FOR EACH ROW
    EXECUTE FUNCTION handle_event_types_standard_name();


