import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    // Auth check - view analytics permission required
    const authResult = await verifyAdminPermission(request, 'canViewAnalytics');
    if ('error' in authResult) return authResult.error;

    const [totalUsers, totalHouses, totalShops, totalProducts, totalOrders, orders] =
      await Promise.all([
        db.user.count(),
        db.house.count(),
        db.shop.count(),
        db.product.count(),
        db.order.count(),
        db.order.findMany({ select: { totalAmount: true } }),
      ]);

    const totalRevenue = orders.reduce((sum, o) => sum + o.totalAmount, 0);

    // Get recent activity
    const recentUsers = await db.user.findMany({
      take: 2,
      orderBy: { createdAt: 'desc' },
      select: { name: true, createdAt: true },
    });

    const recentOrders = await db.order.findMany({
      take: 2,
      orderBy: { createdAt: 'desc' },
      select: { id: true, totalAmount: true, createdAt: true },
    });

    const recentProducts = await db.product.findMany({
      take: 2,
      orderBy: { createdAt: 'desc' },
      select: { title: true, createdAt: true },
    });

    const recentActivity = [
      ...recentUsers.map((u) => ({
        type: 'user',
        title: `New user: ${u.name}`,
        description: 'User registered',
        time: formatTimeAgo(u.createdAt),
      })),
      ...recentOrders.map((o) => ({
        type: 'order',
        title: `Order ৳${o.totalAmount.toLocaleString()}`,
        description: `Order placed`,
        time: formatTimeAgo(o.createdAt),
      })),
      ...recentProducts.map((p) => ({
        type: 'listing',
        title: `New product: ${p.title}`,
        description: 'Product listed',
        time: formatTimeAgo(p.createdAt),
      })),
    ].sort(() => Math.random() - 0.5); // Simple sort for demo

    return NextResponse.json({
      success: true,
      stats: {
        totalUsers,
        totalHouses,
        totalShops,
        totalProducts,
        totalOrders,
        totalRevenue,
        recentActivity,
      },
    });
  } catch (error) {
    console.error('Admin stats error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch stats' },
      { status: 500 }
    );
  }
}

function formatTimeAgo(date: Date): string {
  const now = new Date();
  const diff = now.getTime() - new Date(date).getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (minutes < 1) return 'Just now';
  if (minutes < 60) return `${minutes}m ago`;
  if (hours < 24) return `${hours}h ago`;
  return `${days}d ago`;
}
