const std = @import("std");
const httpz = @import("../.deps/http.zig/src/httpz.zig");
const models = @import("../db/models.zig");
// const ztime = @import("../.deps/time.zig");
const utils = @import("../utils.zig");

const auth = @import("auth.zig");
const handler = @import("../http_handler.zig");

pub fn fetchNotesFromDb(allocator: std.mem.Allocator, family_id: u32) !?[]models.SharedNote {
    var db = handler.getDb();

    const notes = db.selectAllWhere(
        models.SharedNote,
        allocator,
        "WHERE family_id = ? and hide = ?",
        .{ .family_id = family_id, .hide = 0 },
        "updated_at",
        "DESC",
        true,
        10,
    ) catch |err| {
        std.debug.print("Error while getting shared notes: {any}", .{err});
        return err;
    };
    return notes;
}

pub fn getSharedNotes(req: *httpz.Request, res: *httpz.Response) !void {
    var db = handler.getDb();
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    var str_limit: ?[]const u8 = req.param("limit");
    if (str_limit == null) {
        str_limit = "10";
    }
    const limit = std.fmt.parseInt(u32, str_limit.?, 0) catch {
        handler.returnError("Bad Request: Bad Limit", 401, res);
        return;
    };

    const token = auth.verifyRequest(req, res, null, null) catch {
        return;
    };

    const notes = db.selectAllWhere(
        models.SharedNote,
        allocator,
        "WHERE family_id = ? and hide = ?",
        .{ .family_id = token.family_id, .hide = 0 },
        "updated_at",
        "DESC",
        true,
        limit,
    ) catch |err| {
        std.debug.print("Error while getting shared notes: {any}", .{err});
        return err;
    };

    try res.json(.{ .notes = notes }, .{});
    return;
}

pub fn putSharedNote(req: *httpz.Request, res: *httpz.Response) !void {
    var db = handler.getDb();
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    const body_data = req.json(models.SharedNote) catch |err| {
        std.debug.print("Malformed body: {any}\n", .{err});
        handler.returnError("Bad request: Malformed Body", 400, res);
        return;
    };
    if (body_data == null) {
        handler.returnError("Bad request: No Data", 400, res);
        return;
    }
    var shared_note = body_data.?;

    _ = auth.verifyRequest(req, res, shared_note.created_by_user_id, shared_note.family_id) catch {
        return;
    };

    const now = @intCast(u64, std.time.milliTimestamp());
    shared_note.updated_at = now;
    try db.updateById(models.SharedNote, shared_note);

    const updated_note = try db.selectOneById(models.SharedNote, allocator, shared_note.id);
    if (updated_note) |note| {
        try handler.returnData(note, res);
    } else {
        handler.returnError("Internal Server Error", 500, res);
    }
    return;
}

const NotePostReq = struct {
    id: ?u32,
    family_id: u32,
    created_by_user_id: u32,
    content: []const u8,
    title: []const u8,
    color: ?[]const u8,
    tag_ids: []const u8,
    is_markdown: u2,
    created_at: ?u64,
    updated_at: ?u64,
    hide: u8,
};

pub fn postSharedNote(req: *httpz.Request, res: *httpz.Response) !void {
    comptime {
        const postReqLen = @typeInfo(NotePostReq).Struct.fields.len;
        const noteLen = @typeInfo(models.SharedNote).Struct.fields.len;
        if (postReqLen != noteLen) {
            @compileError(std.fmt.comptimePrint("SharedNotePutReq does not equal SharedNote model struct, fields inconsistent", .{}));
        }
    }
    var db = handler.getDb();
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    const body_data = req.json(NotePostReq) catch |err| {
        std.debug.print("Malformed body: {any}\n", .{err});
        handler.returnError("Bad request: Malformed Body", 400, res);
        return;
    };
    if (body_data == null) {
        handler.returnError("Bad request: No Data", 400, res);
        return;
    }
    var body = body_data.?;

    _ = auth.verifyRequest(req, res, body.created_by_user_id, body.family_id) catch {
        return;
    };

    const now = @intCast(u64, std.time.milliTimestamp());
    body.created_at = now;
    body.updated_at = now;

    // remove the null id field for insertion
    try db.insert(models.SharedNote, utils.removeStructFields(body, &[_]u8{0}));

    // Get new SharedNote
    const query = try models.createSelectOnFieldQuery(models.SharedNote, null, "created_at", "=");
    const updated_note = try db.selectOne(models.SharedNote, allocator, query, .{ .created_at = body.created_at });
    if (updated_note) |note| {
        try handler.returnData(note, res);
    } else {
        handler.returnError("Internal Server Error", 500, res);
    }
    return;
}