const express = require("express");
const pool = require("../db"); // PostgreSQL-Datenbankverbindung
const { requireAuth } = require("../middleware/auth"); // Auth-Middleware

const router = express.Router();

// **1. Alle Features abrufen (Falls ID gegeben: Nur dieses Feature)**
router.get("/:id?", requireAuth, async (req, res) => {
  const { id } = req.params;

  try {
    let result;

    if (id) {
      result = await pool.query("SELECT * FROM features WHERE id = $1", [id]);

      if (result.rows.length === 0) {
        return res.status(404).json({ error: "Feature nicht gefunden" });
      }

      return res.json(result.rows[0]);
    } else {
      result = await pool.query(
        "SELECT * FROM features ORDER BY datetime DESC"
      );
      return res.json(result.rows);
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "Interner Serverfehler" });
  }
});

// **2. Feature anlegen oder aktualisieren**
router.put("/:id?", requireAuth, async (req, res) => {
  const { id } = req.params;
  const { title, body, type, urgency, fid_user, datetime, done } = req.body;

  try {
    let result;

    if (id) {
      // **Feature aktualisieren**
      const featureResult = await pool.query(
        "SELECT fid_user FROM features WHERE id = $1",
        [id]
      );

      if (featureResult.rows.length === 0) {
        return res.status(404).json({ error: "Feature nicht gefunden" });
      }

      const featureOwner = featureResult.rows[0].fid_user;

      if (req.user.id !== featureOwner && req.user.id !== 1) {
        return res
          .status(403)
          .json({ error: "Keine Berechtigung, dieses Feature zu bearbeiten" });
      }

      if (done !== undefined && req.user.id !== 1) {
        return res
          .status(403)
          .json({ error: 'Nur User mit ID 1 darf das Feld "done" ändern' });
      }

      if (done !== undefined) {
        result = await pool.query(
          "UPDATE features SET done = $1 WHERE id = $2 RETURNING *",
          [done, id]
        );
      } else {
        if (!title || !body || !type || !urgency) {
          return res
            .status(400)
            .json({ error: "Alle Felder sind erforderlich" });
        }

        result = await pool.query(
          `UPDATE features 
                     SET title = $1, body = $2, type = $3, urgency = $4 
                     WHERE id = $5 
                     RETURNING *`,
          [title, body, type, urgency, id]
        );
      }

      return res.json({
        message: "Feature erfolgreich aktualisiert",
        feature: result.rows[0],
      });
    } else {
      // **Neues Feature anlegen**
      if (!title || !body || !type || !urgency || !fid_user || !datetime) {
        return res
          .status(400)
          .json({ error: 'Alle Felder außer "done" sind erforderlich' });
      }

      result = await pool.query(
        `INSERT INTO features (title, body, type, urgency, fid_user, datetime, done) 
                 VALUES ($1, $2, $3, $4, $5, $6, false) 
                 RETURNING *`,
        [title, body, type, urgency, fid_user, datetime]
      );

      return res.status(201).json({
        message: "Feature erfolgreich angelegt",
        feature: result.rows[0],
      });
    }
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "Interner Serverfehler" });
  }
});

// **3. Feature löschen (Nur durch anlegenden Benutzer oder User ID 1)**
router.delete("/:id", requireAuth, async (req, res) => {
  const { id } = req.params;

  try {
    const featureResult = await pool.query(
      "SELECT fid_user FROM features WHERE id = $1",
      [id]
    );

    if (featureResult.rows.length === 0) {
      return res.status(404).json({ error: "Feature nicht gefunden" });
    }

    const featureOwner = featureResult.rows[0].fid_user;

    if (req.user.id !== featureOwner && req.user.id !== 1) {
      return res
        .status(403)
        .json({ error: "Keine Berechtigung, dieses Feature zu löschen" });
    }

    await pool.query("DELETE FROM features WHERE id = $1", [id]);

    res.json({ message: "Feature erfolgreich gelöscht" });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "Interner Serverfehler" });
  }
});

module.exports = router;
