const express = require("express");
const router = express.Router();
const db = require("../../../database/config");

router.get("/", async (req, res) => {
  try {
    const nomor = req.query.nomor;
    if (nomor != null) {
      db.get("SELECT * FROM hadits WHERE no = " + nomor, (err, data) => {
        if (err) {
          res.status(500).json({ status: 500, message: err.message });
        } else if (!data) {
          res.status(404).json({ status: 404, data: {} });
        } else {
          res.status(200).json({ status: 200, data: data });
        }
      });
    } else {
      db.all(
        "SELECT * FROM hadits ORDER BY CAST(no as INTEGER) ASC",
        (err, data) => {
          if (err) {
            res.status(500).json({ status: 500, message: err.message });
          } else if (!data) {
            res.status(404).json({ status: 404, data: [] });
          } else {
            res.status(200).json({ status: 200, data: data });
          }
        }
      );
    }
  } catch (error) {
    res.status(500).json({ status: 500, message: error.message });
  }
});

router.get("/find", async (req, res) => {
  try {
    const query = req.query.query;
    if (query != null) {
      db.all(
        "SELECT * FROM hadits WHERE judul LIKE '%" +
          query +
          "%' ORDER BY CAST(no as INTEGER) ASC",
        (err, data) => {
          if (err) {
            res.status(500).json({ status: 500, message: err.message });
          } else if (!data) {
            res.status(404).json({ status: 404, data: [] });
          } else {
            res.status(200).json({ status: 200, data: data });
          }
        }
      );
    } else {
      res.status(500).json({
        status: 500,
        message: "Parameter di perlukan (query).",
      });
    }
  } catch (error) {
    res.status(500).json({ status: 500, message: error.message });
  }
});

module.exports = router;
