'use server'

import { APIError } from "@/util/api/error";
import { Post } from "@/models";


export async function tryFetchPost(request:Request, { params }: {params:{slug: string}}){
    await Post.sync();

    const foundPost = await Post.findOne({include:'user',where:{id:params.slug}});
    
    return new Response(JSON.stringify(foundPost),{ 
            status: 200, 
            headers:{
                "Content-Type": "text/JSON" 
            } 
        }
    ); 

}

export async function GET(request:Request, { params }: {params:{slug: string}}){
    try{
        return await tryFetchPost(request, { params });      
    }
    catch(e){
        if (e instanceof APIError){
            return new Response(e.info.responseText,{status:e.info.status});
        }
        else{
            throw e;
        }
    }
}