-- Migration 016: Create events table (audit trail)
-- Event: comprehensive audit trail for all system actions
-- Uses polymorphic actor (team_profile, customer_profile, or system)

-- Audit trail events
CREATE TABLE events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    event_type event_type NOT NULL,

    -- What entity was affected
    entity_type VARCHAR(100) NOT NULL,
    entity_id UUID NOT NULL,

    -- Who triggered the event (polymorphic)
    actor_type VARCHAR(20),  -- 'team_profile', 'customer_profile', or 'system'
    actor_id UUID,

    -- Additional context (old_status, new_status, changed_fields, etc.)
    metadata JSONB NOT NULL DEFAULT '{}'::JSONB,

    -- When the event occurred (business timestamp, may differ from created_at)
    timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Add FK from notifications to events
ALTER TABLE notifications
    ADD CONSTRAINT fk_notifications_event
    FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE SET NULL;

-- High-performance indexes for common query patterns
CREATE INDEX idx_events_entity ON events(entity_type, entity_id);
CREATE INDEX idx_events_actor ON events(actor_type, actor_id);
CREATE INDEX idx_events_timestamp ON events(timestamp DESC);
CREATE INDEX idx_events_type ON events(event_type);
CREATE INDEX idx_events_created ON events(created_at DESC);

-- Composite index for filtering by entity and time
CREATE INDEX idx_events_entity_timestamp ON events(entity_type, entity_id, timestamp DESC);
