import express from 'express';
import { z } from 'zod';
import {
  createTask,
  listTasks,
  getTask,
  updateTask,
  deleteTask,
  reorderTasks
} from '../services/taskService.js';
import {
  createTaskSchema,
  updateTaskSchema,
  listTasksSchema,
  reorderTasksSchema
} from '../validation/schemas.js';
import logger from '../utils/logger.js';

const router = express.Router();

// ============================================================================
// CREATE Task (in Project)
// ============================================================================

router.post('/projects/:projectId/tasks', async (req, res, next) => {
  try {
    const projectId = z.coerce.number().positive().parse(req.params.projectId);
    const validated = createTaskSchema.parse(req.body);
    const task = await createTask(projectId, validated, 1); // created_by: 1 (ParzivalTD)
    
    logger.info({
      message: 'Task created',
      request_id: req.id,
      project_id: projectId,
      task_id: task.id
    });
    
    res.status(201).json({
      status: 'success',
      data: task,
      meta: {
        timestamp: new Date().toISOString(),
        request_id: req.id
      }
    });
  } catch (error) {
    next(error);
  }
});

// ============================================================================
// LIST Tasks (for a Project)
// ============================================================================

router.get('/projects/:projectId/tasks', async (req, res, next) => {
  try {
    const projectId = z.coerce.number().positive().parse(req.params.projectId);
    const validated = listTasksSchema.parse(req.query);
    const { tasks, total } = await listTasks(projectId, validated);
    
    res.json({
      status: 'success',
      data: tasks,
      meta: {
        total,
        limit: validated.limit,
        offset: validated.offset,
        timestamp: new Date().toISOString(),
        request_id: req.id
      }
    });
  } catch (error) {
    next(error);
  }
});

// ============================================================================
// GET Task Detail
// ============================================================================

router.get('/projects/:projectId/tasks/:taskId', async (req, res, next) => {
  try {
    const projectId = z.coerce.number().positive().parse(req.params.projectId);
    const taskId = z.coerce.number().positive().parse(req.params.taskId);
    const task = await getTask(projectId, taskId);
    
    res.json({
      status: 'success',
      data: task,
      meta: {
        timestamp: new Date().toISOString(),
        request_id: req.id
      }
    });
  } catch (error) {
    next(error);
  }
});

// ============================================================================
// UPDATE Task
// ============================================================================

router.put('/projects/:projectId/tasks/:taskId', async (req, res, next) => {
  try {
    const projectId = z.coerce.number().positive().parse(req.params.projectId);
    const taskId = z.coerce.number().positive().parse(req.params.taskId);
    const validated = updateTaskSchema.parse(req.body);
    const task = await updateTask(projectId, taskId, validated);
    
    logger.info({
      message: 'Task updated',
      request_id: req.id,
      project_id: projectId,
      task_id: taskId
    });
    
    res.json({
      status: 'success',
      data: task,
      meta: {
        timestamp: new Date().toISOString(),
        request_id: req.id
      }
    });
  } catch (error) {
    next(error);
  }
});

// ============================================================================
// DELETE Task
// ============================================================================

router.delete('/projects/:projectId/tasks/:taskId', async (req, res, next) => {
  try {
    const projectId = z.coerce.number().positive().parse(req.params.projectId);
    const taskId = z.coerce.number().positive().parse(req.params.taskId);
    await deleteTask(projectId, taskId);
    
    logger.info({
      message: 'Task deleted',
      request_id: req.id,
      project_id: projectId,
      task_id: taskId
    });
    
    res.status(204).send();
  } catch (error) {
    next(error);
  }
});

// ============================================================================
// BULK REORDER Tasks
// ============================================================================

router.post('/projects/:projectId/tasks/reorder', async (req, res, next) => {
  try {
    const projectId = z.coerce.number().positive().parse(req.params.projectId);
    const validated = reorderTasksSchema.parse(req.body);
    const updated = await reorderTasks(projectId, validated.order);
    
    logger.info({
      message: 'Tasks reordered',
      request_id: req.id,
      project_id: projectId,
      updated_count: updated
    });
    
    res.json({
      status: 'success',
      data: {
        updated_count: updated
      },
      meta: {
        timestamp: new Date().toISOString(),
        request_id: req.id
      }
    });
  } catch (error) {
    next(error);
  }
});

export default router;
