/**
 * WhatsApp Quick Reply Controller
 * API endpoints for quick reply management
 *
 * @module WhatsApp
 * @prefix /api/v1/whatsapp/quick-replies
 */

import { Router, Request, Response, NextFunction } from 'express';
import {
  QuickReplyService,
  CreateQuickReplyDto,
  UpdateQuickReplyDto,
  ServiceContext,
} from '../services';

const router = Router();
const quickReplyService = new QuickReplyService();

function getServiceContext(req: Request): ServiceContext {
  const tenantId = req.headers['x-tenant-id'] as string;
  const userId = (req as any).user?.id;
  return { tenantId, userId };
}

/**
 * GET /api/v1/whatsapp/quick-replies
 * List all quick replies
 */
router.get('/', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const { accountId, category, messageType, isActive } = req.query;

    const quickReplies = await quickReplyService.findAll(ctx, {
      accountId: accountId as string,
      category: category as string,
      messageType: messageType as string,
      isActive: isActive === 'true' ? true : isActive === 'false' ? false : undefined,
    });

    return res.json({
      success: true,
      data: quickReplies,
      count: quickReplies.length,
    });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/active
 * Get active quick replies
 */
router.get('/active', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const { accountId } = req.query;
    const quickReplies = await quickReplyService.findActive(ctx, accountId as string);
    return res.json({ success: true, data: quickReplies, count: quickReplies.length });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/search
 * Search quick replies
 */
router.get('/search', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const { q } = req.query;

    if (!q) {
      return res.status(400).json({ error: 'q (query) parameter is required' });
    }

    const quickReplies = await quickReplyService.search(ctx, q as string);
    return res.json({ success: true, data: quickReplies, count: quickReplies.length });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/categories
 * Get all categories
 */
router.get('/categories', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const categories = await quickReplyService.getCategories(ctx);
    return res.json({ success: true, data: categories });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/most-used
 * Get most used quick replies
 */
router.get('/most-used', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const { limit } = req.query;
    const quickReplies = await quickReplyService.getMostUsed(
      ctx,
      limit ? parseInt(limit as string) : 10
    );
    return res.json({ success: true, data: quickReplies });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/by-category/:category
 * Get quick replies by category
 */
router.get('/by-category/:category', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const quickReplies = await quickReplyService.findByCategory(ctx, req.params.category);
    return res.json({ success: true, data: quickReplies, count: quickReplies.length });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/statistics
 * Get quick reply statistics
 */
router.get('/statistics', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const stats = await quickReplyService.getStatistics(ctx);
    return res.json({ success: true, data: stats });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/shortcut/:shortcut
 * Get quick reply by shortcut
 */
router.get('/shortcut/:shortcut', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const quickReply = await quickReplyService.findByShortcut(ctx, req.params.shortcut);
    if (!quickReply) {
      return res.status(404).json({ error: 'Quick reply not found' });
    }

    return res.json({ success: true, data: quickReply });
  } catch (error) {
    return next(error);
  }
});

/**
 * GET /api/v1/whatsapp/quick-replies/:id
 * Get quick reply by ID
 */
router.get('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const quickReply = await quickReplyService.findById(ctx, req.params.id);
    if (!quickReply) {
      return res.status(404).json({ error: 'Quick reply not found' });
    }

    return res.json({ success: true, data: quickReply });
  } catch (error) {
    return next(error);
  }
});

/**
 * POST /api/v1/whatsapp/quick-replies
 * Create a new quick reply
 */
router.post('/', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const data: CreateQuickReplyDto = req.body;

    if (!data.shortcut || !data.title || !data.content) {
      return res.status(400).json({ error: 'shortcut, title, and content are required' });
    }

    const existing = await quickReplyService.findByShortcut(ctx, data.shortcut);
    if (existing) {
      return res.status(409).json({ error: 'Quick reply with this shortcut already exists' });
    }

    const quickReply = await quickReplyService.create(ctx, data);
    return res.status(201).json({ success: true, data: quickReply });
  } catch (error) {
    return next(error);
  }
});

/**
 * PATCH /api/v1/whatsapp/quick-replies/:id
 * Update quick reply
 */
router.patch('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const data: UpdateQuickReplyDto = req.body;

    if (data.shortcut) {
      const existing = await quickReplyService.findByShortcut(ctx, data.shortcut);
      if (existing && existing.id !== req.params.id) {
        return res.status(409).json({ error: 'Quick reply with this shortcut already exists' });
      }
    }

    const quickReply = await quickReplyService.update(ctx, req.params.id, data);
    if (!quickReply) {
      return res.status(404).json({ error: 'Quick reply not found' });
    }

    return res.json({ success: true, data: quickReply });
  } catch (error) {
    return next(error);
  }
});

/**
 * POST /api/v1/whatsapp/quick-replies/:id/use
 * Record usage of quick reply
 */
router.post('/:id/use', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    await quickReplyService.incrementUsage(ctx, req.params.id);
    return res.json({ success: true, message: 'Usage recorded' });
  } catch (error) {
    return next(error);
  }
});

/**
 * POST /api/v1/whatsapp/quick-replies/:id/activate
 * Activate quick reply
 */
router.post('/:id/activate', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const quickReply = await quickReplyService.activate(ctx, req.params.id);
    if (!quickReply) {
      return res.status(404).json({ error: 'Quick reply not found' });
    }

    return res.json({ success: true, data: quickReply });
  } catch (error) {
    return next(error);
  }
});

/**
 * POST /api/v1/whatsapp/quick-replies/:id/deactivate
 * Deactivate quick reply
 */
router.post('/:id/deactivate', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const quickReply = await quickReplyService.deactivate(ctx, req.params.id);
    if (!quickReply) {
      return res.status(404).json({ error: 'Quick reply not found' });
    }

    return res.json({ success: true, data: quickReply });
  } catch (error) {
    return next(error);
  }
});

/**
 * POST /api/v1/whatsapp/quick-replies/:id/duplicate
 * Duplicate quick reply
 */
router.post('/:id/duplicate', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const { shortcut } = req.body;

    if (!shortcut) {
      return res.status(400).json({ error: 'shortcut is required' });
    }

    const existing = await quickReplyService.findByShortcut(ctx, shortcut);
    if (existing) {
      return res.status(409).json({ error: 'Quick reply with this shortcut already exists' });
    }

    const quickReply = await quickReplyService.duplicate(ctx, req.params.id, shortcut);
    if (!quickReply) {
      return res.status(404).json({ error: 'Quick reply not found' });
    }

    return res.status(201).json({ success: true, data: quickReply });
  } catch (error) {
    return next(error);
  }
});

/**
 * DELETE /api/v1/whatsapp/quick-replies/:id
 * Delete quick reply
 */
router.delete('/:id', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const ctx = getServiceContext(req);
    if (!ctx.tenantId) {
      return res.status(400).json({ error: 'X-Tenant-Id header required' });
    }

    const deleted = await quickReplyService.delete(ctx, req.params.id);
    if (!deleted) {
      return res.status(404).json({ error: 'Quick reply not found' });
    }

    return res.json({ success: true, message: 'Quick reply deleted' });
  } catch (error) {
    return next(error);
  }
});

export default router;
