import { NextResponse } from "next/server";
import { uploadFile } from "@/utils/upload.file";
import clientPromise, { database } from "@/db.config";
import { getOrigin, modifyByKeys } from "@/models/helper";

export async function POST(request) {
  const { searchParams } = new URL(request.url);
  const type = searchParams.get("type");
  const origin = await getOrigin();

  try {
    // uploadFile supports multiple files per request.
    // but on this endpoint we only support one file
    const resultUpload = await uploadFile(request, { resize: true });

    if (resultUpload.files.some((file) => file.success === false))
      throw new Error("Failed to upload file");

    // db logic
    const client = await clientPromise;
    const mongo = client.db(database);
    const media = mongo.collection("media");

    const savetodb = await Promise.all(
      resultUpload.files.map(async (item) => {
        const meta = {
          createdAt: new Date(),
          url: item.url,
          title: item.name,
          filename: item.filename,
        };
        const resultDB = await media.insertOne(meta);
        return {
          ...meta,
          _id: resultDB.insertedId,
        };
      })
    );

    const result = {
      ...resultUpload,
      files: resultUpload.files.map((file) => {
        const data = savetodb.find((item) => item.filename === file.filename);
        return modifyByKeys(
          { ...file, ...data },
          ["url"],
          // (url) => `${origin}/api${url}`,
          (url) => `${origin}${url}`,
          true
        );
      }),
    };

    // experimental
    if (type === "mediapost")
      return NextResponse.json(
        { errorMessage: "", resultUpload },
        { status: 200 }
      );

    return NextResponse.json(result, { status: 200 });
  } catch (error) {
    if (type === "mediapost")
      return NextResponse.json(
        { errorMessage: "insert error message", result: [] },
        { status: 500 }
      );

    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
