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


// GET DETAIL TASK DIVISI / GET ONE
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      let allData
      const { id } = context.params;
      const { searchParams } = new URL(request.url);
      const kategori = searchParams.get("cat");

      const data = await prisma.divisionProject.findUnique({
         where: {
            id: String(id),
         },
         select: {
            id: true,
            idDivision: true,
            title: true,
            status: true,
            desc: true,
            reason: true,
            report: true,
            isActive: true,
            Division: {
               select: {
                  name: true
               }
            }
         }
      });

      if (!data) {
         return NextResponse.json({ success: false, message: "Gagal mendapatkan kegiatan, data tidak ditemukan", }, { status: 404 });
      }

      if (kategori == "data") {
         const dataProgress = await prisma.divisionProjectTask.findMany({
            where: {
               isActive: true,
               idProject: String(id)
            },
            orderBy: {
               updatedAt: 'desc'
            }
         })

         const semua = dataProgress.length
         const selesai = _.filter(dataProgress, { status: 1 }).length
         const progress = Math.ceil((selesai / semua) * 100)


         allData = {
            id: data.id,
            idDivision: data.idDivision,
            division: data.Division.name,
            title: data.title,
            status: data.status == 3 ? "batal" : data.status == 2 ? "selesai" : data.status == 1 ? "dikerjakan" : "segera",
            desc: data.desc,
            reason: data.reason,
            report: data.report,
            isActive: data.isActive,
            progress: progress,
         }
      } else if (kategori == "task") {
         const dataProgress = await prisma.divisionProjectTask.findMany({
            where: {
               isActive: true,
               idProject: String(id)
            },
            select: {
               id: true,
               title: true,
               status: true,
               dateStart: true,
               dateEnd: true,
            },
            orderBy: {
               createdAt: 'asc'
            }
         })

         const fix = dataProgress.map((v: any) => ({
            ..._.omit(v, ["dateStart", "dateEnd", "status"]),
            status: v.status == 1 ? "selesai" : "belum selesai",
            dateStart: moment(v.dateStart).format("DD-MM-YYYY"),
            dateEnd: moment(v.dateEnd).format("DD-MM-YYYY"),
         }))

         allData = fix

      } else if (kategori == "file") {
         const dataFile = await prisma.divisionProjectFile.findMany({
            where: {
               isActive: true,
               idProject: String(id)
            },
            select: {
               id: true,
               ContainerFileDivision: {
                  select: {
                     id: true,
                     name: true,
                     extension: true,
                     idStorage: true
                  }
               }
            }
         })

         const fix = dataFile.map((v: any) => ({
            ..._.omit(v, ["ContainerFileDivision"]),
            nameInStorage: v.ContainerFileDivision.id,
            name: v.ContainerFileDivision.name,
            extension: v.ContainerFileDivision.extension,
            idStorage: v.ContainerFileDivision.idStorage,
         }))

         allData = fix

      } else if (kategori == "member") {
         const dataMember = await prisma.divisionProjectMember.findMany({
            where: {
               isActive: true,
               idProject: String(id)
            },
            select: {
               id: true,
               idUser: true,
               User: {
                  select: {
                     name: true,
                     email: true,
                     img: true,
                     Position: {
                        select: {
                           name: true
                        }
                     }
                  }
               }
            }
         })


         const fix = dataMember.map((v: any) => ({
            ..._.omit(v, ["User"]),
            name: v.User.name,
            email: v.User.email,
            img: v.User.img,
            position: v.User.Position.name
         }))

         allData = fix
      } else if (kategori == "link") {
         const dataLink = await prisma.divisionProjectLink.findMany({
            where: {
               isActive: true,
               idProject: String(id)
            },
            orderBy: {
               createdAt: 'asc'
            }
         })

         allData = dataLink
      }

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

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