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

const protocol = @import("eink_feed_protocol");

const server = @import("eink_feed_server");

pub const api = @import("api/root.zig");
pub const endpoints = @import("endpoints/root.zig");
pub const stores = @import("stores/root.zig");

const log = std.log.scoped(.web);

fn onRequest(r: zap.Request) !void {
    r.setStatus(.not_found);
}

pub fn start(allocator: std.mem.Allocator, port: u16, channels_store: *stores.Channels) !void {
    endpoints.ws.init(allocator, channels_store);
    defer endpoints.ws.deinit();

    var listener = zap.Endpoint.Listener.init(
        allocator,
        .{
            .port = port,
            .on_request = onRequest,
            .on_upgrade = endpoints.ws.onUpgrade,
            .max_clients = 1024,
            .max_body_size = 50 * 1024 * 1024,
            .log = true,
        },
    );
    defer listener.deinit();

    var channel_endpoint = endpoints.Channel.init(allocator, channels_store, "/api/channel");
    try listener.register(&channel_endpoint);

    var channel_frame_endpoint = endpoints.ChannelFrame.init(allocator, channels_store, "/api/frame");
    try listener.register(&channel_frame_endpoint);

    try listener.listen();
    log.info("Listening on 0.0.0.0:{d}", .{port});

    zap.start(.{
        .threads = 4,
        .workers = 1,
    });
}
