namespace notebook;

table Book {
    id: UInt8,
    slug: Text,
    primary key(id),
    unique index by_slug {
        key: (slug),
        value: {id},
    },
}

table Note {
    id: UInt8,
    book: UInt8,
    body: Text,
    primary key(id),
    index by_book {
        key: (book, id),
        value: {body},
    },
    foreign key(book) references Book(id),
    check body != "",
}

export write fn create_book(id: UInt8, slug: Text) -> () {
    Book.insert({
        id: id,
        slug: slug,
    });
}

export write fn add(id: UInt8, book: UInt8, body: Text) -> () {
    Note.insert({
        id: id,
        book: book,
        body: body,
    });
}

export fn lookup(id: UInt8) -> Text? {
    return Note.get(id)?.body;
}

export write fn rename(id: UInt8, body: Text) -> () {
    Note.update(id, {
        body: body,
    });
}

export write fn remove(id: UInt8) -> () {
    Note.delete(id);
}

export gen fn titles(book: UInt8) -> Iterator<Text> {
    for entry in Note.by_book.scan(prefix: (book)) {
        yield entry.0;
    }
}

export fn page(book: UInt8, after: UInt8, size: UInt8) -> List<Text> {
    let mut bodies: List<Text> = [];
    for entry in Note.by_book.scan(
        prefix: (book),
        start: (after) exclusive,
        limit: size,
    ) {
        bodies.append(entry.0);
    }
    return bodies;
}
