CREATE UNLOGGED TABLE activity_logs
(
    id          BIGSERIAL PRIMARY KEY,
    family_id   BIGINT REFERENCES families (id) ON DELETE CASCADE,
    user_id     BIGINT       NOT NULL REFERENCES users (id) ON DELETE CASCADE,
    action      TEXT         NOT NULL,
    entity_type TEXT         NOT NULL,
    entity_id   BIGINT,
    description TEXT         NOT NULL,
    created_at  TIMESTAMP    NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_activity_logs_created_at ON activity_logs (created_at DESC);
CREATE INDEX idx_activity_logs_user_id ON activity_logs (user_id);
CREATE INDEX idx_activity_logs_family_id ON activity_logs (family_id);

DO
$$
BEGIN
    IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'cleanup_activity_logs_hourly') THEN
        PERFORM cron.unschedule((SELECT jobid FROM cron.job WHERE jobname = 'cleanup_activity_logs_hourly'));
    END IF;
END
$$;

SELECT cron.schedule(
    'cleanup_activity_logs_hourly',
    '0 * * * *',
    $$DELETE FROM activity_logs WHERE created_at < NOW() - INTERVAL '1 day'$$
);
