import { Request, Response, NextFunction } from 'express';
import prisma from '../utils/db';
import { AuthRequest } from '../middleware/auth.middleware';

export class TaxonomyController {
  // Public/Authenticated: Get all active verticals
  public getVerticals = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const verticals = await prisma.vertical.findMany({
        where: { isActive: true },
        include: {
          _count: {
            select: { assets: true }
          }
        },
        orderBy: { orderIndex: 'asc' },
      });
      res.status(200).json(verticals);
    } catch (err) { next(err); }
  };

  // Public/Authenticated: Get taxonomy metadata with real-time asset counts
  public getTaxonomyMeta = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const [verticals, assets] = await Promise.all([
        prisma.vertical.findMany({
          where: { isActive: true },
          include: { _count: { select: { assets: true } } },
          orderBy: { orderIndex: 'asc' },
        }),
        prisma.asset.findMany({
          select: {
            categoryId: true,
            subcategory: true,
            contentType: true,
            tags: true,
          }
        })
      ]);

      const categoryCounts: Record<string, number> = {};
      const subcategoryCounts: Record<string, number> = {};
      const contentTypeCounts: Record<string, number> = {};
      const tagCounts: Record<string, number> = {};

      assets.forEach(a => {
        if (a.categoryId) {
          categoryCounts[a.categoryId] = (categoryCounts[a.categoryId] || 0) + 1;
        }
        if (a.subcategory) {
          subcategoryCounts[a.subcategory] = (subcategoryCounts[a.subcategory] || 0) + 1;
        }
        if (a.contentType) {
          contentTypeCounts[a.contentType] = (contentTypeCounts[a.contentType] || 0) + 1;
        }
        if (Array.isArray(a.tags)) {
          a.tags.forEach(t => {
            if (t) tagCounts[t] = (tagCounts[t] || 0) + 1;
          });
        }
      });

      res.status(200).json({
        verticals,
        categories: Object.entries(categoryCounts).map(([name, count]) => ({ name, count })),
        subcategories: Object.entries(subcategoryCounts).map(([name, count]) => ({ name, count })),
        contentTypes: Object.entries(contentTypeCounts).map(([name, count]) => ({ name, count })),
        tags: Object.entries(tagCounts).map(([name, count]) => ({ name, count })),
        totalAssets: assets.length,
      });
    } catch (err) { next(err); }
  };

  // Admin: Create Vertical
  public createVertical = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const { name, icon, description, color } = req.body;
      if (!name) return res.status(400).json({ error: 'Name is required' });
      const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '');

      const vertical = await prisma.vertical.create({
        data: { name, slug, icon, description, color }
      });
      res.status(201).json(vertical);
    } catch (err) { next(err); }
  };

  // Admin: Update Vertical
  public updateVertical = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const { id } = req.params;
      const { name, icon, description, color, isActive, orderIndex } = req.body;
      const data: any = {};
      if (name !== undefined) {
        data.name = name;
        data.slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '');
      }
      if (icon !== undefined) data.icon = icon;
      if (description !== undefined) data.description = description;
      if (color !== undefined) data.color = color;
      if (isActive !== undefined) data.isActive = isActive;
      if (orderIndex !== undefined) data.orderIndex = orderIndex;

      const vertical = await prisma.vertical.update({
        where: { id },
        data,
      });
      res.status(200).json(vertical);
    } catch (err) { next(err); }
  };

  // Admin: Delete Vertical
  public deleteVertical = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const { id } = req.params;
      await prisma.vertical.delete({ where: { id } });
      res.status(204).send();
    } catch (err) { next(err); }
  };
}
