import { Router, Request, Response, NextFunction } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { PAYMENTS_ROLES } from '../../utils/roles';
import { validate } from '../../middleware/validate';
import { donationPagesService } from './donation-pages.service';
import {
  createDonationPageSchema,
  updateDonationPageSchema,
  listDonationPagesSchema,
} from './donation-pages.schemas';

const router = Router();

// All routes require PAYMENTS_ROLES
router.use(authenticate, requireRole(...PAYMENTS_ROLES));

// GET /api/payments/admin/donation-pages — list with pagination, search, status
router.get(
  '/',
  validate(listDonationPagesSchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const result = await donationPagesService.findAll(
        req.query as Record<string, unknown> as Parameters<typeof donationPagesService.findAll>[0],
      );
      res.json(result);
    } catch (err) {
      next(err);
    }
  },
);

// GET /api/payments/admin/donation-pages/:id — get by ID
router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const page = await donationPagesService.findById(req.params.id as string);
    res.json(page);
  } catch (err) {
    next(err);
  }
});

// POST /api/payments/admin/donation-pages — create
router.post(
  '/',
  validate(createDonationPageSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const page = await donationPagesService.create(req.body, req.user!.id);
      res.status(201).json(page);
    } catch (err) {
      next(err);
    }
  },
);

// PUT /api/payments/admin/donation-pages/:id — update
router.put(
  '/:id',
  validate(updateDonationPageSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const page = await donationPagesService.update(req.params.id as string, req.body);
      res.json(page);
    } catch (err) {
      next(err);
    }
  },
);

// DELETE /api/payments/admin/donation-pages/:id — delete
router.delete('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    await donationPagesService.delete(req.params.id as string);
    res.json({ success: true });
  } catch (err) {
    next(err);
  }
});

// GET /api/payments/admin/donation-pages/:id/stats — page-specific stats
router.get('/:id/stats', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const stats = await donationPagesService.getPageStats(req.params.id as string);
    res.json(stats);
  } catch (err) {
    next(err);
  }
});

export { router as donationPagesAdminRouter };
