/**
 * Sales Collateral Routes
 * CRUD operations for the centralized sales asset library
 */

import express, { Request, Response } from 'express';
import { body, validationResult } from 'express-validator';
import { getModels } from '../models';
import { authenticateJwtOrApiToken } from '../middleware/dualAuth';

const router = express.Router();
router.use(authenticateJwtOrApiToken);

// ============================================
// COLLATERAL CRUD
// ============================================

// GET all collateral for a company
router.get('/collateral/:companyId', async (req: Request, res: Response) => {
  try {
    const { companyId } = req.params;
    const { SalesCollateral } = getModels();

    if (!req.user!.companyIds.includes(companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    const filter: Record<string, any> = { companyId };

    if (req.query.type) filter.type = req.query.type;
    if (req.query.status) filter.status = req.query.status;
    if (req.query.category) filter.category = req.query.category;
    if (req.query.funnelStage) filter.funnelStage = req.query.funnelStage;
    if (req.query.accessLevel) filter.accessLevel = req.query.accessLevel;
    if (req.query.aiGenerated) filter.aiGenerated = req.query.aiGenerated === 'true';
    if (req.query.isFavorite) filter.isFavorite = req.query.isFavorite === 'true';

    if (req.query.search) {
      const searchRegex = new RegExp(req.query.search as string, 'i');
      filter.$or = [
        { name: searchRegex },
        { description: searchRegex },
        { valueProposition: searchRegex },
      ];
    }

    const collateral = await SalesCollateral.find(filter).sort({ createdAt: -1 });
    res.json({ data: collateral });
  } catch (error: any) {
    console.error('Error fetching sales collateral:', error);
    res.status(500).json({ error: 'Failed to fetch sales collateral', details: error.message });
  }
});

// GET single collateral by ID
router.get('/collateral/detail/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { SalesCollateral } = getModels();
    const collateral = await SalesCollateral.findById(id);

    if (!collateral) {
      res.status(404).json({ error: 'Collateral not found' });
      return;
    }

    if (!req.user!.companyIds.includes(collateral.companyId) && req.user!.role !== 'admin') {
      res.status(403).json({ error: 'Access denied' });
      return;
    }

    res.json({ data: collateral });
  } catch (error: any) {
    console.error('Error fetching collateral:', error);
    res.status(500).json({ error: 'Failed to fetch collateral', details: error.message });
  }
});

// POST create collateral
router.post('/collateral', [
  body('companyId').notEmpty().withMessage('Company ID is required'),
  body('name').notEmpty().withMessage('Name is required'),
  body('type').notEmpty().withMessage('Type is required'),
], async (req: Request, res: Response) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    res.status(400).json({ error: 'Validation failed', details: errors.array() });
    return;
  }

  try {
    const { SalesCollateral } = getModels();
    const collateral = new SalesCollateral(req.body);
    await collateral.save();
    res.status(201).json({ data: collateral });
  } catch (error: any) {
    console.error('Error creating collateral:', error);
    res.status(500).json({ error: 'Failed to create collateral', details: error.message });
  }
});

// PUT update collateral
router.put('/collateral/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { SalesCollateral } = getModels();
    const collateral = await SalesCollateral.findByIdAndUpdate(id, req.body, { new: true, runValidators: true });

    if (!collateral) {
      res.status(404).json({ error: 'Collateral not found' });
      return;
    }

    res.json({ data: collateral });
  } catch (error: any) {
    console.error('Error updating collateral:', error);
    res.status(500).json({ error: 'Failed to update collateral', details: error.message });
  }
});

// DELETE collateral
router.delete('/collateral/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { SalesCollateral } = getModels();
    const collateral = await SalesCollateral.findByIdAndDelete(id);

    if (!collateral) {
      res.status(404).json({ error: 'Collateral not found' });
      return;
    }

    res.json({ data: collateral });
  } catch (error: any) {
    console.error('Error deleting collateral:', error);
    res.status(500).json({ error: 'Failed to delete collateral', details: error.message });
  }
});

// POST bulk import
router.post('/collateral/bulk-import', async (req: Request, res: Response) => {
  try {
    const { items } = req.body;
    if (!Array.isArray(items) || items.length === 0) {
      res.status(400).json({ error: 'Items array is required' });
      return;
    }

    const { SalesCollateral } = getModels();
    const created = await SalesCollateral.insertMany(items);
    res.status(201).json({ data: created });
  } catch (error: any) {
    console.error('Error bulk importing collateral:', error);
    res.status(500).json({ error: 'Failed to bulk import collateral', details: error.message });
  }
});

// ============================================
// CATEGORY CRUD
// ============================================

// GET all categories for a company
router.get('/categories/:companyId', async (req: Request, res: Response) => {
  try {
    const { companyId } = req.params;
    const { ModuleData } = getModels();

    const categories = await ModuleData.find({ moduleId: 'collateral-categories', companyId });
    res.json({ data: categories.map((c: any) => c.data || c) });
  } catch (error: any) {
    console.error('Error fetching collateral categories:', error);
    res.json({ data: [] });
  }
});

// GET single category by ID
router.get('/categories/detail/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { ModuleData } = getModels();
    const category = await ModuleData.findOne({ _id: id, moduleId: 'collateral-categories' });

    if (!category) {
      res.status(404).json({ error: 'Category not found' });
      return;
    }

    res.json({ data: category.data || category });
  } catch (error: any) {
    console.error('Error fetching category:', error);
    res.status(500).json({ error: 'Failed to fetch category', details: error.message });
  }
});

// POST create category
router.post('/categories', async (req: Request, res: Response) => {
  try {
    const { ModuleData } = getModels();
    const category = new ModuleData({
      moduleId: 'collateral-categories',
      companyId: req.body.companyId,
      data: req.body,
    });
    await category.save();
    res.status(201).json({ data: category.data || category });
  } catch (error: any) {
    console.error('Error creating category:', error);
    res.status(500).json({ error: 'Failed to create category', details: error.message });
  }
});

// PUT update category
router.put('/categories/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { ModuleData } = getModels();
    const category = await ModuleData.findOneAndUpdate(
      { _id: id, moduleId: 'collateral-categories' },
      { data: req.body },
      { new: true }
    );

    if (!category) {
      res.status(404).json({ error: 'Category not found' });
      return;
    }

    res.json({ data: category.data || category });
  } catch (error: any) {
    console.error('Error updating category:', error);
    res.status(500).json({ error: 'Failed to update category', details: error.message });
  }
});

// DELETE category
router.delete('/categories/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { ModuleData } = getModels();
    const category = await ModuleData.findOneAndDelete({ _id: id, moduleId: 'collateral-categories' });

    if (!category) {
      res.status(404).json({ error: 'Category not found' });
      return;
    }

    res.json({ data: category.data || category });
  } catch (error: any) {
    console.error('Error deleting category:', error);
    res.status(500).json({ error: 'Failed to delete category', details: error.message });
  }
});

export default router;