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

const RssItem = struct {
    id: i32,
    title: []const u8,
    blob: []const u8,
    content: []const u8,
    created_at: jetzig.jetquery.DateTime,
    updated_at: jetzig.jetquery.DateTime,
};

fn generateRss(items: []const RssItem, allocator: std.mem.Allocator) ![]u8 {
    var list = std.ArrayList(u8).init(allocator);
    const writer = list.writer();

    try writer.print(
        \\<?xml version="1.0" encoding="UTF-8"?>
        \\<rss version="2.0">
        \\<channel>
        \\<title>yuzucchii.xyz</title>
        \\<link>https://yuzucchii.xyz</link>
        \\<description>Personal blog of Yuzu with all kinds of different articles</description>
        \\<atom:link xmlns:atom="http://www.w3.org/2005/Atom" href="https://yuzucchii.xyz/rss" rel="self" type="application/rss+xml"/>
    , .{});

    for (items) |item| {
        try writer.print(
            \\<item>
            \\<title>{s}</title>
            \\<link>https://yuzucchii.xyz/blogs/{d}</link>
            \\<guid>https://yuzucchii.xyz/blogs/{d}</guid>
            \\<description>{s}</description>
        , .{ item.title, item.id, item.id, item.blob });

        try writer.print(
            \\<pubDate>
            \\{s}, {d} {s} {d} {d}:{d}:{d} {s}
            \\</pubDate>
            , .{ // note: Day, DD, MM, YYYY, HH:MM:SS GMT
                item.created_at.dayNameAbbreviated(),
                item.created_at.day(),
                item.created_at.monthNameAbbreviated(),
                item.created_at.year(),
                item.created_at.hour(),
                item.created_at.minute(),
                item.created_at.second(),
                "-0500",
            }
        );

        try writer.print(
            \\</item>
        , .{});
    }

    try writer.writeAll("</channel></rss>");
    return list.toOwnedSlice();
}


// we'll send xml instead
pub fn index(request: *jetzig.Request) !jetzig.View {
    const query = jetzig.database.Query(.Blog).orderBy(.{.created_at = .desc});

    const blogs = try request.repo.all(query);

    var items: std.ArrayList(RssItem) = .init(request.allocator);

    for (blogs) |blog| {
        try items.append(RssItem{
            .id = blog.id,
            .title = blog.title,
            .blob = blog.blob,
            .content = blog.content orelse "<empty>",
            .created_at = blog.created_at,
            .updated_at = blog.updated_at,
        });
    }

    const rss = generateRss(items.toOwnedSlice() catch {
        std.debug.print("lol", .{});
        return request.fail(.bad_request);
    }, request.allocator) catch {
        return request.fail(.bad_request);
    };

    request.response.content_type = "application/rss+xml";
    return request.renderText(rss, .ok);
}

