import { DIR, funUploadFile, prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { createLogUserMobile } from "@/module/user";
import _ from "lodash";
import { NextResponse } from "next/server";


// UPLOAD FILE
export async function POST(request: Request) {
   try {
      const body = await request.formData()
      const dataBody = body.get("data")

      const { idPath, idDivision, user } = JSON.parse(dataBody as string)

      const userMobile = await funGetUserById({ id: String(user) })
      if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
      }

      const cekDivision = await prisma.division.count({
         where: {
            id: String(idDivision),
            isActive: true
         }
      })

      if (cekDivision == 0) {
         return NextResponse.json({ success: false, message: "Gagal mendapatkan divisi, data tidak ditemukan" }, { status: 200 });
      }

      if (idPath != "home") {
         const cekPath = await prisma.divisionDocumentFolderFile.count({
            where: {
               isActive: true,
               id: idPath
            }
         })

         if (cekPath == 0) {
            return NextResponse.json({ success: false, message: "Gagal mendapatkan path, data tidak ditemukan" }, { status: 200 });
         }
      }

      const nameFile = await prisma.divisionDocumentFolderFile.findMany({
         where: {
            idDivision,
            path: idPath,
            category: "FILE",
            isActive: true
         }
      })

      const dataOmit = nameFile.map((v: any) => ({
         ..._.omit(v, [""]),
         file: v.name + '.' + v.extension,
      }))
      let failed = 0
      body.delete("data")
      for (var pair of body.entries()) {
         if (String(pair[0]).substring(0, 4) == "file") {
            const file = body.get(pair[0]) as File
            const fileName = decodeURIComponent(file.name)
            const fExt = file.name.split(".").pop()
            let fName = fileName.replace("." + fExt, "")
            const cek = dataOmit.some((i: any) => i.file == fileName)
            if (cek) {
               const random = Math.floor(Math.random() * 1000)
               fName = `${fName}_${random}`
            }
            const upload = await funUploadFile({ file: file, dirId: DIR.document })
            if (upload.success) {
               const dataInsert = await prisma.divisionDocumentFolderFile.create({
                  data: {
                     name: fName,
                     path: idPath,
                     idDivision,
                     category: "FILE",
                     extension: String(fExt),
                     createdBy: userMobile.id,
                     idStorage: upload.data.id
                  },
                  select: {
                     id: true
                  }
               });

               // create log user
               const log = await createLogUserMobile({ act: 'CREATE', desc: 'User mengupload file baru', table: 'divisionDocumentFolderFile', data: dataInsert.id, user: userMobile.id })
            } else {
               failed++
            }
         }
      }

      if (failed > 0) {
         return NextResponse.json({ success: false, message: "Beberapa file gagal diupload", failed }, { status: 200 });
      }
      return NextResponse.json({ success: true, message: "Berhasil upload file" }, { status: 200 });
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal upload file, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
   }
};