const std = @import("std");
const jetzig = @import("jetzig");

pub const layout = "minimal";

const Article = struct { title: [255]u8, blob: [255]u8 };

pub fn index(request: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    var root = try data.object();
    const cookies = try request.cookies();

    const query = jetzig.database.Query(.Blog).orderBy(.{ .created_at = .desc });

    const tags = try request.repo.all(
        jetzig.database.Query(.Tag).orderBy(.{ .name = .asc }),
    );
    const blogs = try request.repo.all(query);

    try root.put("tags", tags);
    try root.put("articles", blogs);

    const allowed = blk: {
        const session = cookies.get("session") orelse break :blk false;

        const session_query = jetzig.database.Query(.Session)
            .findBy(.{ .session_id = session.value });
        _ = request.repo.execute(session_query) catch break :blk false;
        break :blk true;
    };

    try root.put("allowed", allowed);

    // Render the response and set the response code.
    return request.render(.ok);
}
