import { prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
   const { searchParams } = new URL(request.url);
   const user = searchParams.get('user');
   const divisi = searchParams.get('division');
   const userMobile = await funGetUserById({ id: String(user) })
   const currentYear = new Date().getFullYear();

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

   const data = await prisma.divisionProject.findMany({
      where: {
         isActive: true,
         idDivision: String(divisi),
      },
      select: {
         createdAt: true,
      },
   })

   const dataYear = data.map((item: any) => item.createdAt.getFullYear())
   // Hapus duplikat pakai Set
   const uniqueYears = [...new Set(dataYear)];

   // Tambahkan tahun sekarang kalau belum ada
   if (!uniqueYears.includes(currentYear)) {
      uniqueYears.push(currentYear);
   }

   // (opsional) urutkan dari terbaru ke lama
   uniqueYears.sort((a, b) => b - a);

   const formattedData = uniqueYears.map(year => ({
      id: String(year),
      name: String(year)
   }));



   return NextResponse.json({ success: true, message: "Success", data: formattedData }, { status: 200 });

}