import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
// Convex routing (WU-13): auth domain needs a paginated listUsers query before wiring.

export async function GET(request: NextRequest) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const search = searchParams.get("search");
    const status = searchParams.get("status"); // active, suspended, locked
    const role = searchParams.get("role"); // all, CUSTOMER, STAFF, ADMIN, SUPER_ADMIN
    const country = searchParams.get("country");
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "50");
    const sortBy = searchParams.get("sortBy") || "createdAt"; // createdAt, lastLoginAt, loginCount
    const sortOrder = searchParams.get("sortOrder") || "desc";

    console.log("📊 Fetching users with filters:", {
      search,
      status,
      role,
      country,
      page,
      limit,
      sortBy,
      sortOrder,
    });

    // Build where clause - show all users by default, or filter by specific role
    const where: any = {};

    // Only filter by role if a specific role is selected (not 'all')
    if (role && role !== "all") {
      where.role = role;
    }

    // Search filter
    if (search) {
      where.OR = [
        { name: { contains: search, mode: "insensitive" } },
        { email: { contains: search, mode: "insensitive" } },
        { companyName: { contains: search, mode: "insensitive" } },
        { phoneNumber: { contains: search, mode: "insensitive" } },
      ];
    }

    // Status filter
    if (status === "active") {
      where.isActive = true;
      where.isSuspended = false;
      where.lockedUntil = null;
    } else if (status === "suspended") {
      where.isSuspended = true;
    } else if (status === "locked") {
      where.lockedUntil = { not: null };
    }

    // Country filter
    if (country) {
      where.lastLoginCountry = country;
    }

    // Calculate pagination
    const skip = (page - 1) * limit;

    // Build order by
    const orderBy: any = {};
    orderBy[sortBy] = sortOrder;

    // Fetch users with enhanced data
    const [users, totalCount] = await Promise.all([
      prisma.users.findMany({
        where,
        orderBy,
        skip,
        take: limit,
        select: {
          id: true,
          name: true,
          email: true,
          country: true,
          companyName: true,
          industry: true,
          selectedPackage: true,
          role: true,
          isActive: true,
          isSuspended: true,
          suspendedAt: true,
          suspendedBy: true,
          suspendedReason: true,
          lastLoginAt: true,
          lastLoginIp: true,
          lastLoginCountry: true,
          lastLoginCity: true,
          loginCount: true,
          failedAttempts: true,
          lockedUntil: true,
          createdAt: true,
          updatedAt: true,
          phoneNumber: true,
          stripeCustomerId: true,
          onboardingComplete: true,
          // Organization membership (for staff members)
          organizationMemberships: {
            select: {
              role: true,
              organization: {
                select: {
                  id: true,
                  name: true,
                },
              },
            },
          },
          // Organization owned by user
          ownedOrganization: {
            select: {
              id: true,
              name: true,
            },
          },
          // Count relations
          _count: {
            select: {
              admin_notes: true,
              billing_emails: true,
              login_history: true,
              subscriptions: true,
              audit_logs: true,
            },
          },
        },
      }),
      prisma.users.count({ where }),
    ]);

    console.log(`✅ Fetched ${users.length} users (total: ${totalCount})`);

    // Calculate analytics - count based on current filter or all users
    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

    // Use the same role filter for analytics, or count all if 'all' selected
    const analyticsRoleFilter = role && role !== "all" ? { role } : {};

    const [
      totalUsers,
      activeUsers,
      suspendedUsers,
      lockedUsers,
      newThisWeek,
      activeSubscriptions,
    ] = await Promise.all([
      prisma.users.count({ where: analyticsRoleFilter }),
      prisma.users.count({
        where: { ...analyticsRoleFilter, isActive: true, isSuspended: false },
      }),
      prisma.users.count({
        where: { ...analyticsRoleFilter, isSuspended: true },
      }),
      prisma.users.count({
        where: { ...analyticsRoleFilter, lockedUntil: { not: null } },
      }),
      prisma.users.count({
        where: {
          ...analyticsRoleFilter,
          createdAt: { gte: oneWeekAgo },
        },
      }),
      prisma.subscriptions.count({
        where: {
          status: { in: ["active", "trialing"] },
        },
      }),
    ]);

    // Group by country and industry
    const byCountry: Record<string, number> = {};
    const byIndustry: Record<string, number> = {};
    const byPackage: Record<string, number> = {};

    users.forEach((u) => {
      const country = u.lastLoginCountry || u.country || "Unknown";
      byCountry[country] = (byCountry[country] || 0) + 1;

      const industry = u.industry || "Unknown";
      byIndustry[industry] = (byIndustry[industry] || 0) + 1;

      const pkg = u.selectedPackage || "None";
      byPackage[pkg] = (byPackage[pkg] || 0) + 1;
    });

    const analytics = {
      total: totalUsers,
      active: activeUsers,
      suspended: suspendedUsers,
      locked: lockedUsers,
      newThisWeek,
      activeSubscriptions,
      byCountry,
      byIndustry,
      byPackage,
    };

    // Map users to include account status and organization info
    const enhancedUsers = users.map((u) => {
      // Get organization info - either owned or member of
      const ownedOrg = u.ownedOrganization;
      const memberOrgs = u.organizationMemberships || [];

      // Determine organization name and role
      let organizationName: string | null = null;
      let organizationRole: string | null = null;

      if (ownedOrg) {
        organizationName = ownedOrg.name;
        organizationRole = "OWNER";
      } else if (memberOrgs.length > 0) {
        organizationName = memberOrgs[0].organization.name;
        organizationRole = memberOrgs[0].role;
      }

      return {
        ...u,
        accountStatus: u.isSuspended
          ? "suspended"
          : u.lockedUntil && new Date(u.lockedUntil) > new Date()
            ? "locked"
            : u.isActive
              ? "active"
              : "inactive",
        hasSubscription: u._count.subscriptions > 0,
        organizationName,
        organizationRole,
      };
    });

    return NextResponse.json({
      users: enhancedUsers,
      analytics,
      pagination: {
        page,
        limit,
        total: totalCount,
        totalPages: Math.ceil(totalCount / limit),
        hasMore: skip + users.length < totalCount,
      },
    });
  } catch (error) {
    console.error("❌ Failed to fetch users:", error);
    return NextResponse.json(
      { error: "Failed to fetch users" },
      { status: 500 },
    );
  }
}
