import { getPosts, updatePostMaintainById } from "@/models/posts.model";
import { response } from "@/utils/helper";

export async function GET(request) {
  try {
    const { searchParams } = new URL(request.url);
    const searchParamsData = Object.fromEntries(searchParams.entries());
    const queryRole = {
      page: parseInt(searchParamsData?.page) || 1,
      limit: parseInt(searchParamsData?.limit) || 100,
      sortBy: searchParamsData?.sortBy || "createdAt",
      with: searchParamsData?.with || "desc",
      search: searchParamsData?.search || null,
    };
    const sortRole = {
      asc: 1,
      desc: -1,
    };

    const posts = await getPosts(
      { page: queryRole.page, limit: queryRole.limit },
      { [queryRole.sortBy]: sortRole[queryRole.with] || -1 },
      queryRole.search
    );

    return response(200, "Get post data successfully", posts);
  } catch (error) {
    return response(500, "Internal Server Error", null, {
      error: "Failed to get post data",
    });
  }
}

export async function PATCH(request) {
  try {
    const data = await request.json();
    const result = await updatePostMaintainById(data);

    return response(200, "Update post data successfully", result);
  } catch (error) {
    return response(500, "Internal Server Error", null, {
      error: "Failed to update data",
    });
  }
}
