CREATE TABLE IF NOT EXISTS library_readers (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    reader_token CHAR(64) NOT NULL,
    preferred_language VARCHAR(12) NOT NULL DEFAULT 'en',
    last_path VARCHAR(255) DEFAULT NULL,
    user_agent VARCHAR(255) DEFAULT NULL,
    first_seen_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_seen_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uniq_library_reader_token (reader_token),
    KEY idx_library_readers_last_seen (last_seen_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS library_reader_visits (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    reader_id BIGINT UNSIGNED NOT NULL,
    session_key VARCHAR(64) NOT NULL,
    entry_path VARCHAR(255) DEFAULT NULL,
    started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_activity_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    page_views INT UNSIGNED NOT NULL DEFAULT 1,
    PRIMARY KEY (id),
    UNIQUE KEY uniq_library_reader_visit (reader_id, session_key),
    KEY idx_library_reader_visits_started (reader_id, started_at),
    CONSTRAINT fk_library_reader_visits_reader FOREIGN KEY (reader_id) REFERENCES library_readers(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS library_reader_activities (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    reader_id BIGINT UNSIGNED NOT NULL,
    visit_id BIGINT UNSIGNED DEFAULT NULL,
    document_id INT UNSIGNED DEFAULT NULL,
    event_type VARCHAR(50) NOT NULL,
    page_path VARCHAR(255) DEFAULT NULL,
    context VARCHAR(20) NOT NULL DEFAULT 'public',
    meta_json TEXT DEFAULT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_library_reader_activities_reader_created (reader_id, created_at),
    KEY idx_library_reader_activities_visit (visit_id),
    KEY idx_library_reader_activities_document (document_id),
    CONSTRAINT fk_library_reader_activities_reader FOREIGN KEY (reader_id) REFERENCES library_readers(id) ON DELETE CASCADE,
    CONSTRAINT fk_library_reader_activities_visit FOREIGN KEY (visit_id) REFERENCES library_reader_visits(id) ON DELETE SET NULL,
    CONSTRAINT fk_library_reader_activities_document FOREIGN KEY (document_id) REFERENCES library_documents(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
