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

export async function POST(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      const { isActive, user } = (await request.json());
      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 data = await prisma.division.count({
         where: {
            id: id,
         },
      });

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

      const update = await prisma.division.update({
         where: {
            id: id,
         },
         data: {
            isActive: !isActive,
         },
      });

      // create log user
      const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengedit status data divisi', table: 'division', data: id, user: userMobile.id })

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

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