import { Router } from 'express';
import { LoyaltyController } from '../controllers/loyalty.controller';
import { requireAuth, requireRoles, requirePermissions } from '../../../shared/middleware/auth.middleware';
import { validateBody, validateQuery } from '../../../shared/validation/validation.middleware';
import {
  enrollCustomerSchema,
  listMembershipsQuerySchema,
  earnPointsSchema,
  redeemPointsSchema,
  adjustPointsSchema,
  calculatePointsSchema,
  lookupByCardSchema,
  listTransactionsQuerySchema,
} from '../validation/customers.schema';

export function createLoyaltyRoutes(controller: LoyaltyController): Router {
  const router = Router();

  // Apply auth middleware to all routes
  router.use(requireAuth);

  // ==================== PROGRAM ROUTES ====================

  // Get active program
  router.get(
    '/program',
    requirePermissions(['loyalty.view']),
    controller.getActiveProgram
  );

  // ==================== MEMBERSHIP ROUTES ====================

  // Enroll customer
  router.post(
    '/enroll',
    requirePermissions(['loyalty.enroll']),
    validateBody(enrollCustomerSchema),
    controller.enrollCustomer
  );

  // List memberships
  router.get(
    '/memberships',
    requirePermissions(['loyalty.view']),
    validateQuery(listMembershipsQuerySchema),
    controller.listMemberships
  );

  // Get membership by customer
  router.get(
    '/memberships/customer/:customerId',
    requirePermissions(['loyalty.view']),
    controller.getMembershipByCustomer
  );

  // Get membership by card
  router.get(
    '/memberships/card/:cardNumber',
    requirePermissions(['loyalty.view']),
    controller.getMembershipByCard
  );

  // Get expiring points
  router.get(
    '/memberships/:membershipId/expiring',
    requirePermissions(['loyalty.view']),
    controller.getExpiringPoints
  );

  // Get transaction history
  router.get(
    '/memberships/:membershipId/transactions',
    requirePermissions(['loyalty.view']),
    validateQuery(listTransactionsQuerySchema),
    controller.getTransactionHistory
  );

  // ==================== POINTS ROUTES ====================

  // Calculate points preview
  router.post(
    '/points/calculate',
    requirePermissions(['loyalty.view']),
    validateBody(calculatePointsSchema),
    controller.calculatePoints
  );

  // Earn points
  router.post(
    '/points/earn',
    requirePermissions(['loyalty.earn']),
    validateBody(earnPointsSchema),
    controller.earnPoints
  );

  // Redeem points
  router.post(
    '/points/redeem',
    requirePermissions(['loyalty.redeem']),
    validateBody(redeemPointsSchema),
    controller.redeemPoints
  );

  // Adjust points
  router.post(
    '/points/adjust',
    requireRoles(['admin', 'manager']),
    validateBody(adjustPointsSchema),
    controller.adjustPoints
  );

  return router;
}
