import { prisma } from "@/module/_global";
import _ from "lodash";
import moment from "moment";
import { NextResponse } from "next/server";


// GET ALL DOCUMENT
export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const idDivision = searchParams.get("division");
      const villageId = searchParams.get("desa");
      const path = searchParams.get("path");
      const active = searchParams.get("active");
      const search = searchParams.get("search");
      const page = searchParams.get("page");
      const get = searchParams.get("get");

      let getFix = 10;
      if (get == null || get == undefined || get == "" || _.isNaN(Number(get))) {
         getFix = 10;
      } else {
         getFix = Number(get);
      }

      const dataSkip = page == null || page == undefined ? 0 : Number(page) * getFix - getFix;

      let kondisi: any = {
         Division: {
            idVillage: String(villageId)
         },
         isActive: active == 'false' ? false : true,
         path: (path == "undefined" || path == "null" || path == "" || path == null || path == undefined) ? "home" : path,
         name: {
            contains: (search == undefined || search == "null") ? "" : search,
            mode: "insensitive"
         }
      }

      if (idDivision != "null" && idDivision != undefined && idDivision != "") {
         kondisi = {
            ...kondisi,
            idDivision: String(idDivision)
         }
      }

      let formatDataShare: any[] = [];

      if (path == "home" || path == "null" || path == "undefined" || path == null || path == undefined || path == "") {
         const dataShare = await prisma.divisionDocumentShare.findMany({
            where: {
               isActive: true,
               idDivision: String(idDivision),
               DivisionDocumentFolderFile: {
                  isActive: true
               }
            },
            select: {
               DivisionDocumentFolderFile: {
                  select: {
                     idStorage: true,
                     id: true,
                     category: true,
                     name: true,
                     extension: true,
                     path: true,
                     User: {
                        select: {
                           name: true
                        }
                     },
                     createdAt: true,
                     updatedAt: true
                  }
               }
            },
            orderBy: {
               DivisionDocumentFolderFile: {
                  createdAt: 'desc'
               }
            }
         })

         formatDataShare = dataShare.map((v: any) => ({
            ..._.omit(v, ["DivisionDocumentFolderFile"]),
            idStorage: v.DivisionDocumentFolderFile.idStorage,
            id: v.DivisionDocumentFolderFile.id,
            category: v.DivisionDocumentFolderFile.category,
            name: v.DivisionDocumentFolderFile.name,
            extension: v.DivisionDocumentFolderFile.extension,
            path: v.DivisionDocumentFolderFile.path,
            createdBy: v.DivisionDocumentFolderFile.User.name,
            createdAt: v.DivisionDocumentFolderFile.createdAt,
            updatedAt: v.DivisionDocumentFolderFile.updatedAt,
            share: true
         }))
      }


      const data = await prisma.divisionDocumentFolderFile.findMany({
         skip: dataSkip,
         take: getFix,
         where: kondisi,
         select: {
            id: true,
            category: true,
            name: true,
            extension: true,
            idStorage: true,
            path: true,
            User: {
               select: {
                  name: true
               }
            },
            createdAt: true,
            updatedAt: true
         },
         orderBy: {
            createdAt: 'desc'
         }
      })

      const allData = data.map((v: any) => ({
         ..._.omit(v, ["User", "createdAt", "updatedAt"]),
         createdBy: v.User.name,
         createdAt: v.createdAt,
         updatedAt: v.updatedAt,
         share: false
      }))

      if (formatDataShare.length > 0) {
         allData.push(...formatDataShare)
      }

      const formatData = _.orderBy(allData, ['category', 'createdAt'], ['desc', 'desc']);


      return NextResponse.json({ success: true, message: "Berhasil mendapatkan item", data: formatData }, { status: 200 });

   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal mendapatkan item, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
   }
}