-- ABOUTME: Migration to create event_log_by_location table with cap trigger.
-- ABOUTME: Stores event summaries per location, capped at 500 per location.

-- Event log table for location-scoped event summaries
CREATE TABLE event_log_by_location (
    event_id TEXT PRIMARY KEY,
    location_id TEXT NOT NULL REFERENCES locations(id),
    ts_utc INTEGER NOT NULL,
    type TEXT NOT NULL,
    actor TEXT NOT NULL,
    summary TEXT NOT NULL CHECK(json_valid(summary))
);

-- Index for efficient queries by location and time (newest first)
CREATE INDEX idx_evlog_loc_ts ON event_log_by_location(location_id, ts_utc DESC);

-- Trigger to cap events at 500 per location (keeps newest 500)
CREATE TRIGGER trg_evlog_cap AFTER INSERT ON event_log_by_location
BEGIN
    DELETE FROM event_log_by_location
    WHERE rowid IN (
        SELECT rowid FROM event_log_by_location
        WHERE location_id = NEW.location_id
        ORDER BY ts_utc DESC
        LIMIT -1 OFFSET 500
    );
END;
