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) {
   try {
      const { token, user, category } = (await request.json());

      const userMobile = await funGetUserById({ id: 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 cek = await prisma.tokenDeviceUser.count({
         where: {
            idUser: userMobile.id,
            token
         }
      })

      if (category != "register") {
         // create log user
         const log = await createLogUserMobile({ act: 'LOGIN', desc: 'User login', table: 'user', data: '', user: userMobile.id })
      }

      if (cek == 0 && token != "" && token != undefined && token != null) {
         const data = await prisma.tokenDeviceUser.create({
            data: {
               token,
               idUser: userMobile.id
            }
         });
         return NextResponse.json({ success: true, message: "Berhasil mendaftarkan token" }, { status: 200 });
      }

      return NextResponse.json({ success: true, message: "Token sudah terdaftar" }, { status: 200 })

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


export async function PUT(request: Request) {
   try {
      const { token, user, category } = (await request.json());

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

      if (token != "" && token != undefined && token != null) {
         const data = await prisma.tokenDeviceUser.deleteMany({
            where: {
               token,
               idUser: userMobile.id
            }
         });

      }

      if (category != "unregister") {
         // create log user
         const log = await createLogUserMobile({ act: 'LOGOUT', desc: 'User logout', table: 'user', data: '', user: userMobile.id })
      }

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