const express = require('express');
const router = express.Router();
const pool = require('../db');
const verifyUserToken = require('../middleware/authClient');


/*
|--------------------------------------------------------------------------
| GET TASKS (tasks assigned TO current user)
|--------------------------------------------------------------------------
*/
router.get(
  '/',
  verifyUserToken,
  async (req, res) => {
    const { userId, organizationId } = req.user;
//console.log("TASKS HIT");
    try {
      const [tasks] = await pool.query(
        `
        SELECT
          t.taskID,
          t.description,
          t.isCompleted,
          t.dateAdded,
          t.dateCompleted,
          t.projectId,
          t.createdByUserId
        FROM tasks t
        WHERE
          t.organizationId = ?
          AND t.assignedUserId = ?
        ORDER BY t.dateAdded DESC
        `,
      [organizationId, userId]
      );

console.log("QUERY SUCCESS");
      res.json({ success: true, tasks });

    } catch (err) {
      console.error('Error fetching tasks:', err);
      res.status(500).json({
        success: false,
        message: 'Failed to retrieve tasks'
      });
    }
  }
);

/*
|--------------------------------------------------------------------------
| ADD TASK
| - Self task OR assigned to another user
|--------------------------------------------------------------------------
*/

router.post('/', verifyUserToken, async (req, res) => {
  try {
    const { description, assignedUserId, projectId = null } = req.body;

    const userId = req.user.userId;
    const organizationId = req.user.organizationId;

    if (!description || !assignedUserId) {
      return res.status(400).json({
        message: 'Missing required fields'
      });
    }

    /* --------------------------------
       RULE 1: PERSONAL TASK
       projectId = NULL
    --------------------------------- */
    if (!projectId) {
      if (assignedUserId !== userId) {
        return res.status(400).json({
          message: 'Personal tasks can only be assigned to yourself'
        });
      }
    }

    /* --------------------------------
       RULE 2: PROJECT TASK
       projectId IS NOT NULL
    --------------------------------- */
    if (projectId) {
      const [[member]] = await pool.query(
        `
        SELECT 1
        FROM project_users
        WHERE projectId = ?
          AND userId = ?
          AND organizationId = ?
        LIMIT 1
        `,
        [projectId, assignedUserId, organizationId]
      );

      if (!member) {
        return res.status(403).json({
          message: 'Assigned user is not a member of this project'
        });
      }
    }

    /* --------------------------------
       INSERT TASK
    --------------------------------- */
    const [result] = await pool.query(
      `
      INSERT INTO tasks
        (organizationId, description, assignedUserId, projectId, createdByUserId, isCompleted, dateAdded)
      VALUES
        (?, ?, ?, ?, ?, 0, NOW())
      `,
      [
        organizationId,
        description,
        assignedUserId,
        projectId,
        userId
      ]
    );

    return res.json({
      success: true,
      taskID: result.insertId
    });

  } catch (err) {
    console.error('Error adding task:', err);
    return res.status(500).json({
      message: 'Failed to add task'
    });
  }
});

/*
|--------------------------------------------------------------------------
| UPDATE TASK (mark complete / incomplete)
| ❗ Only CREATOR can update
|--------------------------------------------------------------------------
*/
router.put(
  '/',
  verifyUserToken,
  async (req, res) => {
    const { taskID, isCompleted } = req.body;
    const { userId, organizationId } = req.user;

    if (!Number.isInteger(taskID)) {
      return res.status(400).json({ message: 'Invalid task ID' });
    }

    if (typeof isCompleted !== 'boolean') {
      return res.status(400).json({ message: 'isCompleted must be boolean' });
    }

    try {
      const dateCompleted = isCompleted ? new Date() : null;

      const [result] = await pool.query(
        `
        UPDATE tasks
        SET isCompleted = ?, dateCompleted = ?
        WHERE
          taskID = ?
          AND createdByUserId = ?
          AND organizationId = ?
        `,
        [isCompleted, dateCompleted, taskID, userId, organizationId]
      );

      if (result.affectedRows === 0) {
        return res.status(403).json({
          message: 'Task not found or you are not allowed to update it'
        });
      }

      req.app.get('io')?.emit('task_updated', { organizationId });

      res.sendStatus(200);

    } catch (err) {
      console.error('Error updating task:', err);
      res.status(500).json({ message: 'Failed to update task' });
    }
  }
);

/*
|--------------------------------------------------------------------------
| DELETE TASK
| ❗ Only CREATOR can delete
|--------------------------------------------------------------------------
*/
router.delete(
  '/',
  verifyUserToken,
  async (req, res) => {
    const { taskID } = req.body;
    const { userId, organizationId } = req.user;

    if (!Number.isInteger(taskID)) {
      return res.status(400).json({ message: 'Invalid task ID' });
    }

    try {
      const [result] = await pool.query(
        `
        DELETE FROM tasks
        WHERE
          taskID = ?
          AND createdByUserId = ?
          AND organizationId = ?
        `,
        [taskID, userId, organizationId]
      );

      if (result.affectedRows === 0) {
        return res.status(403).json({
          message: 'Task not found or you are not allowed to delete it'
        });
      }

      req.app.get('io')?.emit('task_updated', { organizationId });

      res.sendStatus(200);

    } catch (err) {
      console.error('Error deleting task:', err);
      res.status(500).json({ message: 'Failed to delete task' });
    }
  }
);

module.exports = router;
