import { objectId } from "@/db.config";
import { getJadwalPelatihanByPostId } from "@/models/jadwal.pelatihan";
import {
  createPostMaintain,
  getPostMaintainByBridgeId,
} from "@/models/posts.model";
import { getPostCategories, getTags } from "@/models/term";
import { getUserBridge } from "@/models/users";
import { response } from "@/utils/helper";

export async function GET(request, { params, searchParams }) {
  try {
    const { bridgeId } = await params;
    const { searchParams } = new URL(request.url);
    const query = Object.fromEntries(searchParams.entries());

    let postData = await getPostMaintainByBridgeId(bridgeId);
    const bridgeUser = await getUserBridge();

    if (!postData) {
      if (!Object.keys(query).includes("createnew"))
        return response(404, "Post not found", null);

      postData = await createPostMaintain(bridgeUser._id, {
        bridgeId: objectId(bridgeId),
      });
    }

    const categories = await getPostCategories();
    const tags = await getTags();

    // Optional Data
    const jadwalPelatihan = await getJadwalPelatihanByPostId(postData._id);

    return response(200, "Get Post Data Successfully", {
      post: postData,
      tags,
      categories,
      additionalData: { jadwalPelatihan },
    });
  } catch (error) {
    return response(500, "Internal Server Error", null, { error });
  }
}
