// Identity. Store your memories and mental belongings
// Copyright (C) 2024  SofĂ­a Aritz
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.


import { randomUUID } from "node:crypto";
import list from "./list.js";

export default function registerRoutes(app, auth) {
    list(app, auth);

    app.delete("/entry", {
        async handler(request) {
            let jwt = request.headers["authorization"].replace("Bearer", "").trim();
            let { payload } = await auth.verifyJwt(jwt);

            let user = await auth.user(payload.uid);
            user.entries = user.entries.filter((v) => v.id !== request.query.entry_id);

            await auth.updateUser(payload.uid, user);
        },
        schema: {
            headers: { $ref: "schema://identity/authorization" },
            query: {
                type: "object",
                properties: {
                    entry_id: { type: "string" },
                },
                required: ["entry_id"],
            },
        },
    });

    app.put("/entry", {
        async handler(request) {
            let jwt = request.headers["authorization"].replace("Bearer", "").trim();
            let { payload } = await auth.verifyJwt(jwt);

            let user = await auth.user(payload.uid);
            request.body.entry.id = randomUUID().toString();
            user.entries = [request.body.entry, ...user.entries];

            await auth.updateUser(payload.uid, user);
        },
        schema: {
            headers: { $ref: "schema://identity/authorization" },
            body: {
                type: "object",
                properties: {
                    entry: { type: "object" },
                },
                required: ["entry"],
            },
        },
    });
}