'use server'

import { APIError, attemptAPIAction } from "@/util/api/error";
import { Auth, Post, PostTag, Tag, User, dbSync } from "@/models";
import { cookies } from "next/headers";



async function tryCreatePost(request: Request) {
    // Make sure the DB is ready
    const sync = await dbSync;
    // Prepare data
    const requestBody = await request.json();
    const authCkie = await cookies().get("auth");
    // Sanity check auth cookie
    if ( !authCkie || !authCkie.value)  throw new APIError({ status: 500, responseText: "missing auth cookie" });
    // Get JSON from the Cookie
    const cookieJSON = authCkie.value;
    const authObject = JSON.parse(cookieJSON);
    // Fetch User Auth from the database
    const auth = await Auth.findOne({ 
        include: [
            { 
                model: User.withScope(['withPerms']),
                attributes: {
                    exclude: ['username', 'password', 'updatedAt', 'createdAt']
                }
            }
        ],
        where: { token: authObject.token } 
    });
    
    // Sanity check the auth and associated user
    if (!auth || !auth.user)                            throw new APIError({ status: 401, responseText: "Authentication Error" });

    // Handle incomplete data or other problems
    if (!requestBody)                                   throw new APIError({ status: 500, responseText: "Empty request body" });
    if (!requestBody.title)                             throw new APIError({ status: 500, responseText: "Missing post title" });
    if (!requestBody.content)                           throw new APIError({ status: 500, responseText: "Missing post content" });
    if (!requestBody.description)                       throw new APIError({ status: 500, responseText: "Missing post description" });
    if (!auth.user.id)                                  throw new APIError({ status: 500, responseText: "Missing user id" });
    if (!auth.user.perms || !auth.user.perms.isAdmin)   throw new APIError({ status: 401, responseText: `Unauthorized ${JSON.stringify(auth.user)}` });

    // Create a new Post in the database
    const post = await Post.create(
    {
        content: requestBody.content,
        description: requestBody.description,
        user_id: auth.user.id,
        title: requestBody.title,
    },{
        include: {
            association: Post.associations.user
        }
    }).then(post=>post.reload())

    // Return the response
    return new Response(JSON.stringify(post), { status: 200 });

}



export async function tryFetchPosts(request: Request) {

    await Post.sync();

    const foundPosts = await Post.findAll({
        include: [
        {
            association: Post.associations.user,
            attributes: { exclude: ['password', 'createdAt', 'updatedAt'] }
        },{
            association: Post.associations.postTags
        }]
    });

    return new Response(JSON.stringify(foundPosts), { status: 200 });

}

export async function GET(request: Request) {
    return await attemptAPIAction(tryFetchPosts,request);
}
export async function POST(request: Request) {
    return await attemptAPIAction(tryCreatePost,request);
}
