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 Users
router.get('/', authenticate, async (req: Request, res: Response) => {
  try {
    const { skip, take, ...where } = req.query;
    const Users = await prisma.user.findMany({
      where: where as any,
      skip: skip ? parseInt(skip as string) : undefined,
      take: take ? Math.min(parseInt(take as string), 100) : 20,
    });
    res.json(Users);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

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

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

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

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

export default router;
