import { Router } from "express";
import Project from "../models/Project";

const router = Router();

router.get("/", async (_req, res) => {
  try {
    const projects = await Project.find().sort({ releaseDate: -1 });

    return res.json(projects);
  } catch (error) {
    if (error instanceof Error) {
      return res.json({ error: error.message });
    }
  }
});

router.get("/:id", async (req, res) => {
  try {
    const project = await Project.findById(req.params.id);

    return res.json(project);
  } catch (error) {
    if (error instanceof Error) {
      return res.json({ error: error.message });
    }
  }
});

router.post("/", async (req, res) => {
  try {
    const project = await Project.create(req.body);

    return res.json(project);
  } catch (error) {
    if (error instanceof Error) {
      return res.json({ error: error.message });
    }
  }
});

router.put("/:id", async (req, res) => {
  try {
    const project = await Project.findByIdAndUpdate(req.params.id, req.body, {
      upsert: true,
      new: true,
    });

    return res.json(project);
  } catch (error) {
    if (error instanceof Error) {
      return res.json({ error: error.message });
    }
  }
});

router.delete("/:id", async (req, res) => {
  try {
    const project = await Project.findByIdAndDelete(req.params.id);

    return res.json(project);
  } catch (error) {
    if (error instanceof Error) {
      return res.json({ error: error.message });
    }
  }
});

const projectRoute = router;
export default projectRoute;
