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

const router = Router();

// Public: get FAQs (homepage-visible only by default; pass ?all=true for all)
router.get('/', async (req: Request, res: Response) => {
  try {
    const showAll = req.query.all === 'true';
    const faqs = await prisma.faq.findMany({
      where: showAll ? undefined : { showOnHomepage: true },
      orderBy: { order: 'asc' },
    });
    res.json(faqs);
  } catch (err) {
    console.error('List public FAQs error:', err);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// Admin: get all FAQs regardless of visibility
router.get(
  '/all',
  requireAuth,
  requires('faq.manage'),
  async (_req: Request, res: Response) => {
    try {
      const faqs = await prisma.faq.findMany({
        orderBy: { order: 'asc' },
      });
      res.json(faqs);
    } catch (err) {
      console.error('List all FAQs error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

// Admin: create FAQ
router.post(
  '/',
  requireAuth,
  requires('faq.manage'),
  async (req: Request, res: Response) => {
    try {
      const { question, answer, showOnHomepage } = req.body;

      if (!question || !answer) {
        res.status(400).json({ error: 'question and answer are required' });
        return;
      }

      const maxOrder = await prisma.faq.aggregate({ _max: { order: true } });
      const nextOrder = (maxOrder._max.order ?? -1) + 1;

      const faq = await prisma.faq.create({
        data: {
          question,
          answer,
          order: nextOrder,
          showOnHomepage: showOnHomepage !== undefined ? showOnHomepage : true,
        },
      });

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

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

      const { question, answer, showOnHomepage } = req.body;
      const updateData: any = {};
      if (question !== undefined) updateData.question = question;
      if (answer !== undefined) updateData.answer = answer;
      if (showOnHomepage !== undefined) updateData.showOnHomepage = showOnHomepage;

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

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

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

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

// Admin: reorder FAQs — accepts array of { id, order }
router.post(
  '/reorder',
  requireAuth,
  requires('faq.manage'),
  async (req: Request, res: Response) => {
    try {
      const { items } = req.body as { items: { id: string; order: number }[] };
      if (!Array.isArray(items)) {
        res.status(400).json({ error: 'items array is required' });
        return;
      }

      await Promise.all(
        items.map(({ id, order }) =>
          prisma.faq.update({ where: { id }, data: { order } })
        )
      );

      res.json({ success: true });
    } catch (err) {
      console.error('Reorder FAQs error:', err);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);

export default router;
