import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { createLogUser } from "@/module/user";
import { NextResponse } from "next/server";


// HAPUS PROJECT YG TELAH DIBATALKAN
export async function DELETE(request: Request, context: { params: { id: string } }) {
   try {
      const user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }

      const { id } = context.params
      const data = await prisma.project.count({
         where: {
            id: id,
         }
      })

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

      const dataDelete = await prisma.project.update({
         where: {
            id
         },
         data: {
            isActive: false
         }
      })

      // create log user
      const log = await createLogUser({ act: 'DELETE', desc: 'User menghapus data kegiatan', table: 'project', data: String(id) })
      return NextResponse.json({ success: true, message: "Kegiatan berhasil dihapus", user: user.id }, { status: 200 });

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

// EDIT PROJECT REPORT
export async function PUT(request: Request, context: { params: { id: string } }) {
   try {
      const user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }

      const { id } = context.params
      const { report } = await request.json()

      const data = await prisma.project.count({
         where: {
            id: id
         }
      })

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

      const dataCreate = await prisma.project.update({
         where: {
            id
         },
         data: {
            report: report
         }
      })

      // create log user
      const log = await createLogUser({ act: 'UPDATE', desc: 'User mengupdate laporan kegiatan', table: 'project', data: String(id) })

      return NextResponse.json({ success: true, message: "Laporan kegiatan berhasil diupdate" }, { status: 200 });

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