import { Router, Request, Response } from 'express';
import { prisma } from '../database/prisma';
import { authenticate, authorize } from '../middleware/auth';
import { validateRequest } from '../middleware/validation';

const router = Router();

// List all Tasks
router.get('/', authenticate, async (req: Request, res: Response) => {
  try {
    const { skip, take, ...where } = req.query;
    const Tasks = await prisma.task.findMany({
      where: where as any,
      skip: skip ? parseInt(skip as string) : undefined,
      take: take ? Math.min(parseInt(take as string), 100) : 20,
    });
    res.json(Tasks);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

// Get Task by ID
router.get('/:id', authenticate, async (req: Request, res: Response) => {
  try {
    const Task = await prisma.task.findUnique({
      where: { id: req.params.id },
    });
    if (!Task) {
      return res.status(404).json({ message: 'Task not found' });
    }
    res.json(Task);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

// Create Task
router.post('/', authenticate, async (req: Request, res: Response) => {
  try {
    const Task = await prisma.task.create({
      data: req.body,
    });
    res.status(201).json(Task);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

// Update Task
router.put('/:id', authenticate, async (req: Request, res: Response) => {
  try {
    const Task = await prisma.task.update({
      where: { id: req.params.id },
      data: req.body,
    });
    res.json(Task);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

// Delete Task
router.delete('/:id', authenticate, async (req: Request, res: Response) => {
  try {
    const Task = await prisma.task.update({
      where: { id: req.params.id },
      data: { deleted_at: new Date() },
    });
    res.json(Task);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

export default router;
