import { Router } from 'express';
import type { Request, Response } from 'express';
import { requireRole } from '../../middleware/rbac.middleware';
import { SOCIAL_ROLES } from '../../utils/roles';
import { referralService } from './referral.service';
import { createInviteCodeSchema, validateCodeSchema, paginationSchema } from './referral.schemas';

const router = Router();

/** POST /api/social/referrals/codes — create invite code */
router.post('/codes', async (req: Request, res: Response) => {
  try {
    const data = createInviteCodeSchema.parse(req.body);
    const code = await referralService.createInviteCode(req.user!.id, data);
    res.status(201).json(code);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'CREATE_CODE_ERROR' } });
  }
});

/** GET /api/social/referrals/codes — list my codes */
router.get('/codes', async (req: Request, res: Response) => {
  try {
    const { page, limit } = paginationSchema.parse(req.query);
    const result = await referralService.listMyCodes(req.user!.id, page, limit);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'LIST_CODES_ERROR' } });
  }
});

/** DELETE /api/social/referrals/codes/:id — deactivate code */
router.delete('/codes/:id', async (req: Request, res: Response) => {
  try {
    const codeId = req.params.id as string;
    const result = await referralService.deactivateCode(req.user!.id, codeId);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'DEACTIVATE_CODE_ERROR' } });
  }
});

/** GET /api/social/referrals/validate/:code — validate an invite code */
router.get('/validate/:code', async (req: Request, res: Response) => {
  try {
    const { code } = validateCodeSchema.parse(req.params);
    const result = await referralService.validateCode(code);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'VALIDATE_CODE_ERROR' } });
  }
});

/** GET /api/social/referrals/my-referrals — list people I referred */
router.get('/my-referrals', async (req: Request, res: Response) => {
  try {
    const { page, limit } = paginationSchema.parse(req.query);
    const result = await referralService.getMyReferrals(req.user!.id, page, limit);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'MY_REFERRALS_ERROR' } });
  }
});

/** GET /api/social/referrals/stats — my referral stats */
router.get('/stats', async (req: Request, res: Response) => {
  try {
    const stats = await referralService.getReferralStats(req.user!.id);
    res.json(stats);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'REFERRAL_STATS_ERROR' } });
  }
});

/** GET /api/social/referrals/admin/all — all referrals (admin only) */
router.get('/admin/all', requireRole(...SOCIAL_ROLES), async (req: Request, res: Response) => {
  try {
    const { page, limit } = paginationSchema.parse(req.query);
    const result = await referralService.listAllReferrals(page, limit);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'ADMIN_REFERRALS_ERROR' } });
  }
});

/** GET /api/social/referrals/admin/leaderboard — top referrers (admin only) */
router.get('/admin/leaderboard', requireRole(...SOCIAL_ROLES), async (req: Request, res: Response) => {
  try {
    const limit = parseInt((req.query.limit as string) || '10', 10);
    const leaderboard = await referralService.getReferralLeaderboard(Math.min(limit, 50));
    res.json({ leaderboard });
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'LEADERBOARD_ERROR' } });
  }
});

export { router as referralRouter };
