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

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);
    return request.render(.ok);
}

pub fn post(request: *jetzig.Request) !jetzig.View {
    // delete entry
    const cookies = try request.cookies();
    const session = cookies.get("session") orelse {
        return request.redirect("/login", .moved_permanently);
    };

    const query = jetzig.database.Query(.Session)
        .findBy(.{ .session_id = session.value });

    _ = request.repo.execute(query) catch {
        return request.redirect("/login", .moved_permanently);
    };

    // delete it
    const delete_query = jetzig.database.Query(.Session)
        .delete()
        .where(.{ .{ .session_id, .eql, session.value } });

    _ = request.repo.execute(delete_query) catch {
        return request.fail(.internal_server_error);
    };

    // delete cookie
    try cookies.put(.{
        .name = "session",
        .value = "",
        .path = "/",
        .max_age = 0,
        .http_only = true,
        .secure = false,
        .expires = 0,
    });

    try request.headers.append("Set-Cookie",
    "session=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax");

    std.debug.print("Deleting session cookie at path: {?s}\n", .{session.path});

    return request.render(.ok);
}

