"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateCustomer = exports.getCustomers = void 0;
const client_1 = require("@prisma/client");
const prisma = new client_1.PrismaClient();
// GET /api/admin/customers
const getCustomers = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { search, role, status } = req.query;
        // 1. Build dynamic filter object
        const whereClause = {};
        if (search) {
            whereClause.OR = [
                { fullName: { contains: String(search), mode: 'insensitive' } },
                { email: { contains: String(search), mode: 'insensitive' } },
            ];
        }
        if (role && role !== 'ALL')
            whereClause.role = role;
        // Note: 'status' isn't in your schema yet, but often mapped to 'isArchived' or a specific field.
        // For this example, we'll assume a new field 'isActive' or similar exists, or skip if not in schema.
        // 2. Fetch Users with Aggregates
        const users = yield prisma.user.findMany({
            where: whereClause,
            include: {
                _count: {
                    select: { orders: true }, // Count number of orders
                },
                orders: {
                    where: { isPaid: true }, // Only sum paid orders
                    select: { total: true },
                },
            },
            orderBy: { createdAt: 'desc' },
            take: 50, // Pagination limit
        });
        // 3. Transform Data for UI
        // Prisma returns orders as an array, we need to sum them up manually or use aggregate separately.
        // Doing it in JS here is fine for <100 records per page.
        const formattedUsers = users.map((user) => {
            const totalSpent = user.orders.reduce((acc, order) => acc + Number(order.total), 0);
            return {
                id: user.id,
                name: user.fullName || 'Unknown',
                email: user.email,
                role: user.role,
                orders: user._count.orders,
                spent: new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(totalSpent),
                status: user.emailVerified ? 'Active' : 'Pending', // Deriving status from verification, or add a specific field
                joinedAt: user.createdAt,
            };
        });
        res.json(formattedUsers);
    }
    catch (error) {
        console.error('Get Customers Error:', error);
        res.status(500).json({ error: 'Failed to fetch customers' });
    }
});
exports.getCustomers = getCustomers;
// PUT /api/admin/customers/:id
const updateCustomer = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { id } = req.params;
        const { role, status } = req.body;
        // Validation
        if (!id)
            return res.status(400).json({ error: 'User ID required' });
        const updatedUser = yield prisma.user.update({
            where: { id },
            data: {
                role: role, // 'USER', 'ADMIN', 'SUPPORT'
            },
        });
        res.json({ message: 'User updated successfully', user: updatedUser });
    }
    catch (error) {
        console.error('Update Customer Error:', error);
        res.status(500).json({ error: 'Failed to update customer' });
    }
});
exports.updateCustomer = updateCustomer;
