const std = @import("std");
const jetzig = @import("jetzig");
const uuid4 = @import("uuid").v4;

pub const layout = "panel";

pub fn index(request: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    const cookies = try request.cookies();
    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;
    };

    const root = try data.object();
    try root.put("allowed", allowed);

    if (cookies.get("session")) |session| if (session.value.len != 0)
        return request.redirect("/blogs", .moved_permanently);

    return request.render(.ok);
}

pub fn post(request: *jetzig.Request) !jetzig.View {
    // ask for password
    const cookies = try request.cookies();

    const env_map = try request.allocator.create(std.process.EnvMap);
    env_map.* = try std.process.getEnvMap(request.allocator);
    defer env_map.deinit();

    const secrets = @import("dev").BLOGS_PASSWORD;

    std.debug.print("body data: {s}\n", .{request.body});

    const login_data = std.json.parseFromSliceLeaky(struct {
        password: []const u8,
    }, request.allocator, request.body, .{}) catch {
        return request.fail(.bad_request);
    };

    var buf: [0x100]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&buf);
    const allocator = fba.allocator();

    if (std.mem.eql(u8, login_data.password, secrets)) {
        // logged in, creating cookie
        const uuid = try std.fmt.allocPrint(allocator, "{d}", .{uuid4.new()});

        try cookies.put(.{
            .name = "session",
            .value = uuid,
            .path = "/",
            .domain = @import("dev").DOMAIN,
            .same_site = .lax,
            .http_only = true,
            .secure = false,
            .max_age = 60 * 60 * 24 * 7, // 1 week
            .partitioned = false,
        });

        // post to Session table

        try request.repo.insert(.Session, .{ .session_id = uuid });

        return request.render(.created);
    } else {
        return request.fail(.unauthorized);
    }
}
