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.program.findFirst({
    select: {
      id: true,
      course: true,
      subject: true,
      content: true,
      tag: true,
      status: true,
      publish_at: true,
      updated_at: true,
      created_at: 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 { course, subject, content, tag, status, publish_at } = req.body
  const result = await prisma.program.update({
    where: { id: id },
    data: {
      course,
      subject,
      content,
      tag,
      status,
      publish_at,
    },
  })

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

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