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

const router = Router();

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

router.get('/by-slug/:slug', async (req: Request, res: Response) => {
  try {
    const organizer = await prisma.organizer.findUnique({
      where: { slug: req.params.slug as string },
    });
    if (!organizer) {
      res.status(404).json({ error: 'Organizer not found' });
      return;
    }
    res.json(organizer);
  } catch (err) {
    console.error('Get organizer by slug error:', err);
    if (respondIfOrganizerMigrationNeeded(err, res)) return;
    res.status(500).json({ error: 'Internal server error' });
  }
});

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

      const organizer = await prisma.organizer.create({
        data: { name, slug },
      });

      res.status(201).json(organizer);
    } catch (err: any) {
      if (err?.code === 'P2002') {
        res.status(400).json({ error: 'An organizer with this slug already exists' });
        return;
      }
      console.error('Create organizer error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

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

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

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

      res.json(updated);
    } catch (err: any) {
      if (err?.code === 'P2002') {
        res.status(400).json({ error: 'An organizer with this slug already exists' });
        return;
      }
      console.error('Update organizer error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

router.delete(
  '/:id',
  requireAuth,
  requires('organizers.manage'),
  async (req: Request, res: Response) => {
    try {
      const organizer = await prisma.organizer.findUnique({
        where: { id: req.params.id as string },
        include: { _count: { select: { meetups: true } } },
      });
      if (!organizer) {
        res.status(404).json({ error: 'Organizer not found' });
        return;
      }
      if (organizer._count.meetups > 0) {
        res.status(400).json({
          error: `Cannot delete organizer: ${organizer._count.meetups} event(s) still reference it`,
        });
        return;
      }

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

export default router;
