import { Router, Request, Response, NextFunction } from 'express';
import { petitionsService } from './petitions.service';
import { signPetitionSchema } from './petitions.schemas';
import { validate } from '../../../middleware/validate';
import { petitionSignRateLimit } from '../../../middleware/rate-limit';

const router = Router();

// GET /api/petitions/public?page=1&limit=20 — list active petitions (paginated)
router.get(
  '/public',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const page = Math.max(parseInt(req.query.page as string) || 1, 1);
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 50);
      const result = await petitionsService.findActivePetitions(page, limit);
      res.json(result);
    } catch (err) { next(err); }
  }
);

// GET /api/petitions/:slug/details — public petition data (ACTIVE only)
router.get(
  '/:slug/details',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const slug = req.params.slug as string;
      const petition = await petitionsService.findBySlugPublic(slug);
      res.json(petition);
    } catch (err) { next(err); }
  }
);

// GET /api/petitions/:slug/signers — public signature list
router.get(
  '/:slug/signers',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const slug = req.params.slug as string;
      const page = parseInt(req.query.page as string) || 1;
      const limit = Math.min(parseInt(req.query.limit as string) || 20, 50);
      const result = await petitionsService.listSignaturesPublic(slug, page, limit);
      res.json(result);
    } catch (err) { next(err); }
  }
);

// GET /api/petitions/:slug/public-stats — public signature counts + geo
router.get(
  '/:slug/public-stats',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const slug = req.params.slug as string;
      const petition = await petitionsService.findBySlugPublic(slug);
      const stats = await petitionsService.getStats(petition.id);
      res.json(stats);
    } catch (err) { next(err); }
  }
);

// POST /api/petitions/:slug/sign — sign petition
router.post(
  '/:slug/sign',
  petitionSignRateLimit,
  validate(signPetitionSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const slug = req.params.slug as string;
      const ip = (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() || req.ip || '';
      const result = await petitionsService.signPetition(slug, req.body, ip);
      res.status(result.alreadySigned ? 200 : 201).json(result);
    } catch (err) { next(err); }
  }
);

// Verification route
const verifyRouter = Router();

// GET /api/petitions/verify/:token — email verification
verifyRouter.get(
  '/verify/:token',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const token = req.params.token as string;
      const result = await petitionsService.verifySignature(token);
      const title = result.alreadyVerified ? 'Already Confirmed' : 'Signature Confirmed';
      const msg = result.alreadyVerified
        ? 'Your signature was already confirmed. Thank you for your support!'
        : 'Your signature has been verified. Thank you for adding your voice!';

      res.send(`<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${title}</title>
<style>body{font-family:-apple-system,BlinkMacSystemFont,sans-serif;display:flex;justify-content:center;align-items:center;min-height:100vh;margin:0;background:#0d1b2a;color:#e0e0e0}
.card{background:#1b2838;padding:2rem;border-radius:12px;text-align:center;max-width:400px;box-shadow:0 4px 20px rgba(0,0,0,.3)}
h1{color:#3498db;margin-bottom:.5rem}p{line-height:1.6;color:#a0a0a0}</style>
</head><body><div class="card"><h1>${title}</h1><p>${msg}</p></div></body></html>`);
    } catch (err) { next(err); }
  }
);

export { router as petitionsPublicRouter, verifyRouter as petitionVerifyRouter };
