import { Router, Request, Response } from 'express';
import { prisma } from '../db/prisma';
import { requireAuth, requires } from '../middleware/auth';

const router = Router();

router.get('/', async (_req: Request, res: Response) => {
  try {
    const categories = await prisma.category.findMany({
      orderBy: { sortOrder: 'asc' },
    });
    res.json(categories);
  } catch (err) {
    console.error('List categories error:', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

router.post(
  '/',
  requireAuth,
  requires('categories.manage'),
  async (req: Request, res: Response) => {
    try {
      const { name, slug, sortOrder } = req.body;
      if (!name || !slug) {
        res.status(400).json({ error: 'name and slug are required' });
        return;
      }

      const category = await prisma.category.create({
        data: {
          name,
          slug,
          sortOrder: sortOrder || 0,
        },
      });

      res.status(201).json(category);
    } catch (err) {
      console.error('Create category error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.patch(
  '/:id',
  requireAuth,
  requires('categories.manage'),
  async (req: Request, res: Response) => {
    try {
      const category = await prisma.category.findUnique({
        where: { id: req.params.id as string },
      });
      if (!category) {
        res.status(404).json({ error: 'Category not found' });
        return;
      }

      const { name, slug, sortOrder } = req.body;
      const updateData: any = {};
      if (name !== undefined) updateData.name = name;
      if (slug !== undefined) updateData.slug = slug;
      if (sortOrder !== undefined) updateData.sortOrder = sortOrder;

      const updated = await prisma.category.update({
        where: { id: req.params.id as string },
        data: updateData,
      });

      res.json(updated);
    } catch (err) {
      console.error('Update category error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.delete(
  '/:id',
  requireAuth,
  requires('categories.manage'),
  async (req: Request, res: Response) => {
    try {
      const category = await prisma.category.findUnique({
        where: { id: req.params.id as string },
      });
      if (!category) {
        res.status(404).json({ error: 'Category not found' });
        return;
      }

      await prisma.category.delete({ where: { id: req.params.id as string } });
      res.json({ success: true });
    } catch (err) {
      console.error('Delete category error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

export default router;
