import { exec } from "child_process"
import { NextResponse } from "next/server"

import { verifyUserRole } from "@/services/auth.service"

export async function POST() {
  try {
    await verifyUserRole("ADMIN")
  } catch (error) {
    console.error(error)
    return new NextResponse("Unauthorized", { status: 403 })
  }

  return new Promise<NextResponse>((resolve) => {
    exec("bunx prisma migrate reset --force", (error, stdout, stderr) => {
      if (error) {
        console.error(`Error: ${error.message}`)
        return resolve(
          new NextResponse("Error al resetear la base de datos", {
            status: 500,
          }),
        )
      }
      if (stderr) {
        console.error(`stderr: ${stderr}`)
        return resolve(
          new NextResponse("Error al resetear la base de datos", {
            status: 500,
          }),
        )
      }

      console.log(`stdout: ${stdout}`)
      return resolve(
        new NextResponse("Base de datos reseteada con éxito", { status: 200 }),
      )
    })
  })
}
