import { Router, Request, Response } from 'express';
import prisma from '../lib/prisma.js';

const router = Router();

router.get('/', async (req: Request, res: Response) => {
  try {
    const { page = '1', limit = '24', q, verified, developerId } = req.query;
    const pageNum = Math.max(1, parseInt(page as string));
    const limitNum = Math.min(100, Math.max(1, parseInt(limit as string)));

    const where: any = {};
    if (typeof q === 'string' && q.trim()) {
      where.OR = [
        { companyName: { contains: q.trim() } },
        { user: { firstName: { contains: q.trim() } } },
        { user: { lastName: { contains: q.trim() } } },
      ];
    }
    if (verified === 'true') {
      where.verificationStatus = 'VERIFIED';
    }
    
    // Filter by developer if provided
    let userIdsFilter: string[] | undefined;
    if (typeof developerId === 'string' && developerId.trim()) {
      const devAgents = await (prisma as any).developerAgent.findMany({
        where: { developerId: developerId.trim() },
        select: { userId: true },
      });
      userIdsFilter = devAgents.map((da: any) => da.userId);
      if (userIdsFilter.length === 0) {
        // No agents for this developer, return empty result
        return res.json({
          agents: [],
          pagination: {
            currentPage: pageNum,
            totalItems: 0,
            itemsPerPage: limitNum,
          },
        });
      }
      where.userId = { in: userIdsFilter };
    }

    const [rows, total] = await Promise.all([
      (prisma as any).agentProfile.findMany({
        where,
        include: {
          user: {
            select: { id: true, firstName: true, lastName: true, profilePicture: true },
          },
        },
        orderBy: [
          { verificationStatus: 'asc' },
          { user: { firstName: 'asc' } },
          { user: { lastName: 'asc' } },
          { companyName: 'asc' },
        ],
        skip: (pageNum - 1) * limitNum,
        take: limitNum,
      }),
      (prisma as any).agentProfile.count({ where }),
    ]);

    const userIds = rows.map((r) => r.userId);
    const activeCounts = await prisma.property.groupBy({
      by: ['ownerId'],
      where: {
        ownerId: { in: userIds },
        status: 'ACTIVE',
      },
      _count: { _all: true },
    });
    const activeCountByUser = new Map(activeCounts.map((c) => [c.ownerId, c._count._all] as const));

    const devAgents = await (prisma as any).developerAgent.findMany({
      where: { userId: { in: userIds } },
      include: { developer: true },
    });
    const developerByUser = new Map<string, any>(devAgents.map((da: any) => [da.userId, da.developer]));

    res.json({
      agents: rows.map((r) => {
        const dev = developerByUser.get(r.userId) || null;
        return {
          id: r.id,
          userId: r.userId,
          companyName: r.companyName,
          bio: r.bio,
          licenseNumber: r.licenseNumber,
          verificationStatus: r.verificationStatus,
          contactPhone: r.contactPhone,
          contactEmail: r.contactEmail,
          logoUrl: r.logoUrl,
          websiteUrl: r.websiteUrl,
          user: r.user,
          activeListingsCount: activeCountByUser.get(r.userId) ?? 0,
          developer: dev
            ? {
                id: dev.id,
                name: dev.name,
                licenseNumber: dev.licenseNumber,
                verified: dev.verified,
              }
            : null,
        };
      }),
      pagination: {
        currentPage: pageNum,
        totalItems: total,
        itemsPerPage: limitNum,
      },
    });
  } catch (error: any) {
    console.error('List agents error:', error);
    res.status(500).json({ error: 'Failed to fetch agents', message: error.message });
  }
});

router.get('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;

    const agent = await (prisma as any).agentProfile.findUnique({
      where: { id },
      include: {
        user: {
          select: { id: true, firstName: true, lastName: true, profilePicture: true },
        },
      },
    });

    if (!agent) {
      return res.status(404).json({ error: 'Agent not found' });
    }

    const activeListingsCount = await prisma.property.count({
      where: { ownerId: agent.userId, status: 'ACTIVE' },
    });

    const devAgent = await (prisma as any).developerAgent.findUnique({
      where: { userId: agent.userId },
      include: { developer: true },
    });
    const dev = devAgent?.developer || null;

    res.json({
      agent: {
        id: agent.id,
        userId: agent.userId,
        companyName: agent.companyName,
        bio: agent.bio,
        licenseNumber: agent.licenseNumber,
        verificationStatus: agent.verificationStatus,
        contactPhone: agent.contactPhone,
        contactEmail: agent.contactEmail,
        logoUrl: agent.logoUrl,
        websiteUrl: agent.websiteUrl,
        user: agent.user,
        activeListingsCount,
        developer: dev
          ? {
              id: dev.id,
              name: dev.name,
              licenseNumber: dev.licenseNumber,
              verified: dev.verified,
            }
          : null,
      },
    });
  } catch (error: any) {
    console.error('Get agent error:', error);
    res.status(500).json({ error: 'Failed to fetch agent', message: error.message });
  }
});

router.get('/:id/properties', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { page = '1', limit = '12' } = req.query;
    const pageNum = Math.max(1, parseInt(page as string));
    const limitNum = Math.min(100, Math.max(1, parseInt(limit as string)));

    const agent = await (prisma as any).agentProfile.findUnique({ where: { id }, select: { userId: true } });
    if (!agent) {
      return res.status(404).json({ error: 'Agent not found' });
    }

    const where: any = { ownerId: agent.userId, status: 'ACTIVE' };

    const [properties, total] = await Promise.all([
      prisma.property.findMany({
        where,
        include: {
          photos: { orderBy: { order: 'asc' } },
        },
        orderBy: [{ featured: 'desc' }, { createdAt: 'desc' }],
        skip: (pageNum - 1) * limitNum,
        take: limitNum,
      }),
      prisma.property.count({ where }),
    ]);

    res.json({
      properties,
      pagination: {
        currentPage: pageNum,
        totalItems: total,
        itemsPerPage: limitNum,
      },
    });
  } catch (error: any) {
    console.error('Agent properties error:', error);
    res.status(500).json({ error: 'Failed to fetch agent properties', message: error.message });
  }
});

export default router;
