-- Migration: Event Access Control
-- Date: 2026-02-03
-- Description: Adds access control fields to norda_events and is_rada_member to users
-- Purpose: Allow restricting events to specific groups (Rada Izby vs all members)

-- =====================================================
-- 1. Add access control fields to norda_events
-- =====================================================

-- access_level: 'public' (all logged in), 'members_only' (MEMBER+), 'rada_only' (only Rada Izby members)
ALTER TABLE norda_events
ADD COLUMN IF NOT EXISTS access_level VARCHAR(50) DEFAULT 'members_only';

COMMENT ON COLUMN norda_events.access_level IS 'Event visibility: public, members_only, rada_only';

-- Update existing events based on event_type
-- Rada Izby events should be rada_only
UPDATE norda_events
SET access_level = 'rada_only'
WHERE title ILIKE '%Rada Izby%' OR event_type = 'rada';

-- Other events are members_only by default
UPDATE norda_events
SET access_level = 'members_only'
WHERE access_level IS NULL;

-- =====================================================
-- 2. Add is_rada_member field to users
-- =====================================================

ALTER TABLE users
ADD COLUMN IF NOT EXISTS is_rada_member BOOLEAN DEFAULT FALSE;

COMMENT ON COLUMN users.is_rada_member IS 'User is a member of Rada Izby (Board Council)';

-- =====================================================
-- 3. Create index for faster event filtering
-- =====================================================

CREATE INDEX IF NOT EXISTS idx_norda_events_access_level
ON norda_events(access_level);

-- =====================================================
-- 4. Grant permissions
-- =====================================================

GRANT ALL ON TABLE norda_events TO nordabiz_app;
GRANT ALL ON TABLE users TO nordabiz_app;

-- =====================================================
-- Verification
-- =====================================================

DO $$
BEGIN
    -- Check if columns exist
    IF EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'norda_events' AND column_name = 'access_level'
    ) THEN
        RAISE NOTICE 'Column norda_events.access_level created successfully';
    END IF;

    IF EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name = 'users' AND column_name = 'is_rada_member'
    ) THEN
        RAISE NOTICE 'Column users.is_rada_member created successfully';
    END IF;
END $$;
