import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default defineEventHandler( async (event) => {
    console.log("This is a test for a POST request to the backend");
    
    // const successMsg = "Hello from the backend";

    const body = await readBody(event);

    if (!body) {
        return {
            status: 400,
            message: "Body was not received"
        }
    }

    /*
    This is a sample of the expected body data structure:
    {
        cabinet_name: "Cabinet 1",
        cabinet_parent_id: "", // NULL means its a root folder and has no parents.
        cabinet_owner: "", // OPTIONAL
        cabinet_sector: "", // Dunno??? Has a max length of 7 characters.
        dp_id: "", // LEAVE NULL department ID. Foreign key. Is disabled for development purposes.
        userID: "", // LEAVE NULL User ID. Foreign key. Is disabled for development purposes.
    }
    */

    // The following are functions to check the body data structure.

    console.log(body.cabinet_name);

    if (!body.cabinet_name || !body.cabinet_sector) {
        return {
            status: 400,
            message: "cabinet_name and cabinet_sector are required"
        };
    };

    // Checked body data.
    const folderData = {
        cb_name: body.cabinet_name,
        cb_parent_id: body.cabinet_parent_id,
        cb_owner: body.cabinet_owner,
        cb_sector: body.cabinet_sector,
        dp_id: body.dp_id,
        userID: body.userID,
        created_at: new Date(),
        modified_at: new Date()
    };

    // Create new folder using checked data.
    const newFolder =  await prisma.cabinets.create({ data: folderData })

    return {
        status: 201,
        message: "Folder created successfully",
        folder: newFolder
    };
    
});