import { generateUUID } from "@/helpers/uuid.helper"
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 === "POST") {
    return create(req, res)
  } else {
    return res.status(405).json({ error: "Method not allowed" })
  }
}

async function get(req: NextApiRequest, res: NextApiResponse) {
  const accesstoken = req.query.accesstoken ? (req.query.accesstoken as string) : ""
  const program_id = req.query.program_id ? (req.query.program_id as string) : ""
  const page = req.query.page ? Number(req.query.page) : 1
  const pageSize = req.query.limit ? Number(req.query.limit) : 10
  const start = (page - 1) * pageSize

  // const user = await prisma.admin.findFirst({
  //   where: { accesstoken },
  //   select: {
  //     id: true,
  //   },
  // })

  // if (!user) {
  //   return res.status(400).json({ message: "Invalid user" })
  // }

  const total = await prisma.quiz.count()
  const totalPage = Math.ceil(total / pageSize)
  const where = program_id === "" ? {} : { program_id }
  const result = await prisma.quiz.findMany({
    select: {
      id: true,
      program_id: true,
      sequence: true,
      quiz_type: true,
      question: true,
      choice: true,
      hint: true,
    },
    where: where,
    orderBy: {
      sequence: "asc",
    },
    skip: start,
    take: pageSize,
  })

  res.status(200).json({
    data: result,
    page: page,
    pageSize: pageSize,
    totalPage: totalPage,
    total: total,
    start: start,
  })
}

async function create(req: NextApiRequest, res: NextApiResponse) {
  console.log("req.body", req.body)

  const { program_id, sequence, quiz_type, question, choice, answer, comment, hint } = req.body
  let id = generateUUID()
  const result = await prisma.quiz.create({
    data: {
      id,
      program_id,
      quiz_type,
      sequence,
      question,
      choice,
      answer,
      comment,
      hint,
    },
  })

  if (!result) {
    return res.status(400).json({ message: "Error" })
  }

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