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 orders = prisma 

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

app.get("/orders/:id", async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);
  const order = await prisma.order.findUnique({
    where: { id },
  });

  if (!order) {
    return res.status(404).json({ error: "Order not found" });
  }

  res.json(order);
});

app.post("/orders", async (req: Request, res: Response) => {
  const { name, pizza } = req.body;

  if (!name || !pizza) {
    return res.status(400).json({ error: "Name and pizza is required!" });
  }

  const newOrder = await prisma.order.create({
    data: { name, pizza },
  });

  res.status(201).json(newOrder);
});

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

  if (!name || !pizza) {
    return res.status(400).json({ error: "Name and pizza is required!" });
  }

  try {
    const updatedOrder = await prisma.order.update({
      where: { id },
      data: { name, pizza }
    });
    res.json(updatedOrder);
  } catch {
    return res.status(404).json({ error: "Order not found" });
  }
});

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

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

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

  try {
    const updatedOrder = await prisma.order.update({
      where: { id },
      data
    });
    
    res.json(updatedOrder);
  } catch {
    return res.status(404).json({ error: "Order not found" });
  }
});

app.delete("/orders/:id", async (req: Request, res: Response) => {
  const id = parseInt(req.params.id);
  try {
    await prisma.order.delete({
      where: { id },
    });
    return res.status(204).send();
  } catch {
    return res.status(404).json({ error: "Order not found" });
  }
});

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