import { Router, Response } from 'express';
import prisma from '../lib/prisma.js';
import { authenticateToken, AuthRequest } from '../middleware/auth.middleware.js';

const router = Router();

router.get('/developers', async (_req, res: Response) => {
  try {
    const developers = await (prisma as any).developer.findMany({
      where: { verified: true },
      orderBy: { name: 'asc' },
    });
    res.json({ developers });
  } catch (error: any) {
    console.error('Developer list error:', error);
    res.status(500).json({ error: 'Failed to load developers', message: error.message });
  }
});

const getDeveloperForUser = async (userId: string) => {
  const mapping = await (prisma as any).developerAgent.findUnique({
    where: { userId },
    include: { developer: true },
  });
  return mapping?.developer || null;
};

router.get('/overview', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required' });

    const developer = await getDeveloperForUser(userId);
    if (!developer) {
      return res.status(403).json({ error: 'Not a developer account' });
    }

    const [agentCount, propertyCount, activePropertyCount] = await Promise.all([
      (prisma as any).developerAgent.count({ where: { developerId: developer.id } }),
      prisma.property.count({ where: { developerId: developer.id } }),
      prisma.property.count({ where: { developerId: developer.id, status: 'ACTIVE' } }),
    ]);

    res.json({
      developer,
      stats: {
        agentCount,
        propertyCount,
        activePropertyCount,
      },
    });
  } catch (error: any) {
    console.error('Developer overview error:', error);
    res.status(500).json({ error: 'Failed to load developer overview', message: error.message });
  }
});

router.get('/agents', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required' });

    const developer = await getDeveloperForUser(userId);
    if (!developer) {
      return res.status(403).json({ error: 'Not a developer account' });
    }

    const agents = await (prisma as any).developerAgent.findMany({
      where: { developerId: developer.id },
      include: {
        user: { select: { id: true, firstName: true, lastName: true, email: true, phone: true, role: true } },
      },
      orderBy: { createdAt: 'desc' },
    });

    res.json({ agents });
  } catch (error: any) {
    console.error('Developer agents error:', error);
    res.status(500).json({ error: 'Failed to load developer agents', message: error.message });
  }
});

router.get('/properties', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required' });

    const developer = await getDeveloperForUser(userId);
    if (!developer) {
      return res.status(403).json({ error: 'Not a developer account' });
    }

    const { page = '1', limit = '20' } = req.query;
    const pageNum = Math.max(1, parseInt(String(page)) || 1);
    const limitNum = Math.min(100, Math.max(1, parseInt(String(limit)) || 20));

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

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

export default router;
