import express, { Request, Response } from "express";
import process from "node:process";
import { fromFileUrl } from "@std/path";
import { dirname } from "@std/path";
import path from "node:path";
import { PrismaClient } from "./generated/client.ts";

const prisma = new PrismaClient();
const __dirname = dirname(fromFileUrl(import.meta.url));
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());

app.use(express.static(path.join(__dirname, "public")));

const students = await prisma.student.findMany();

app.get("/students", async (_req: Request, res: Response) => {
  const students = await prisma.student.findMany();
  res.json(students);
});

app.get("/students/:id", async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);
  const student = await prisma.student.findUnique({
    where: { id }
  });
  if (!student) {
    return res.status(404).json({ error: "Student not found" });
  }
  res.json(student);
});

app.post("/students", async (req: Request, res: Response) => {
  const { name, course } = req.body;
  if (!name || !course) {
    return res.status(400).json({ error: "Name and course are required!" });
  }
  const newStudent = await prisma.student.create({
    data: { name, course }
  });
  res.status(201).json(newStudent);
});

app.put("/students/:id", async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);
  const { name, course } = req.body;
  if (!name || !course) {
    return res.status(400).json({ error: "Name and course are required!" });
  }
  try {
    const updatedStudent = await prisma.student.update({
      where: { id },
      data: { name, course }
    });
    res.json(updatedStudent);
  } catch {
    return res.status(404).json({ error: "Student not found" });
  }
});

app.patch("/students/:id", async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);
  const { name, course } = req.body;

  const data: { name?: string; course?: string } = {};

  if (name !== undefined) data.name = name;
  if (course !== undefined) data.course = course;

  try {
    const updatedStudent = await prisma.student.update({
      where: { id },
      data
    });

    res.json(updatedStudent);
  } catch {
    return res.status(404).json({ error: "Student not found" });
  }
});

app.delete("/students/:id", async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);

  try {
    await prisma.student.delete({
      where: { id }
    });

    return res.status(204).send(); // No Content
  } catch {
    return res.status(404).json({ error: "Student not found" });
  }
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});