import prisma from "@/lib/prismadb"
import type { NextApiRequest, NextApiResponse } from "next"

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "GET") {
    return get(req, res)
  } else if (req.method === "PUT") {
    return update(req, res)
  } else {
    return res.status(405).json({ error: "Method not allowed" })
  }
}

async function get(req: NextApiRequest, res: NextApiResponse) {
  const id = req.query.slug as string
  const result = await prisma.quiz.findFirst({
    select: {
      id: true,
      quiz_type: true,
      sequence: true,
      program_id: true,
      question: true,
      choice: true,
      answer: true,
      comment: true,
      hint: true,
    },
    where: {
      id,
    },
  })

  if (!result) {
    return res.status(400).json({ error: "no data" })
  }

  res.status(200).json(result)
}

async function update(req: NextApiRequest, res: NextApiResponse) {
  const id = req.query.slug as string
  const { quiz_type, sequence, program_id, question, choice, answer, comment, hint } = req.body
  const result = await prisma.quiz.update({
    where: { id },
    data: {
      quiz_type,
      sequence,
      program_id,
      question,
      choice,
      answer,
      comment,
      hint,
    },
  })

  if (!result) {
    return res.status(400).json({ error: "update fail" })
  }

  return res.status(200).json(result)
}
