import { Router, Request, Response } from 'express';
import { prisma } from '../index';
import { asyncHandler } from '../middleware/errorHandler';
import { authenticateToken, AuthenticatedRequest } from '../middleware/auth';
import Joi from 'joi';
import { v4 as uuidv4 } from 'uuid';

const router = Router();

// Validation schemas
const subscribeSchema = Joi.object({
  email: Joi.string().email().required(),
});

// Subscribe to notifications
router.post('/subscribe', asyncHandler(async (req: Request, res: Response) => {
  const { error, value } = subscribeSchema.validate(req.body);
  
  if (error) {
    return res.status(400).json({
      success: false,
      message: error.details[0].message,
    });
  }

  const { email } = value;

  // Check if already subscribed
  const existing = await prisma.subscription.findUnique({
    where: { email },
  });

  if (existing) {
    if (existing.isActive) {
      return res.status(400).json({
        success: false,
        message: 'Email is already subscribed',
      });
    } else {
      // Reactivate subscription
      await prisma.subscription.update({
        where: { email },
        data: { isActive: true },
      });
    }
  } else {
    // Create new subscription
    await prisma.subscription.create({
      data: {
        email,
        unsubscribeToken: uuidv4(),
      },
    });
  }

  res.json({
    success: true,
    message: 'Successfully subscribed to notifications',
  });
}));

// Admin endpoint - Get all subscribers
router.get('/', authenticateToken, asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  const subscribers = await prisma.subscription.findMany({
    orderBy: { createdAt: 'desc' },
    select: {
      id: true,
      email: true,
      isActive: true,
      createdAt: true,
    },
  });

  const stats = {
    total: subscribers.length,
    active: subscribers.filter(sub => sub.isActive).length,
    inactive: subscribers.filter(sub => !sub.isActive).length,
  };

  res.json({
    success: true,
    subscribers,
    stats,
  });
}));

// Admin endpoint - Toggle subscriber status
router.put('/:id/toggle', authenticateToken, asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  const subscriberId = parseInt(req.params.id);
  
  if (isNaN(subscriberId)) {
    return res.status(400).json({
      success: false,
      message: 'Invalid subscriber ID',
    });
  }

  const subscriber = await prisma.subscription.findUnique({
    where: { id: subscriberId },
  });

  if (!subscriber) {
    return res.status(404).json({
      success: false,
      message: 'Subscriber not found',
    });
  }

  const updated = await prisma.subscription.update({
    where: { id: subscriberId },
    data: { isActive: !subscriber.isActive },
  });

  res.json({
    success: true,
    message: `Subscriber ${updated.isActive ? 'activated' : 'deactivated'} successfully`,
    subscriber: updated,
  });
}));

export default router;
