import type { Request, Response, NextFunction } from 'express';
import * as svc from '../services/admin-clientes.service.js';
import { isPlatformStaff } from '../utils/platform-admin.js';
import { AppError } from '../middlewares/error.middleware.js';

async function requireStaff(req: Request) {
  if (!req.user?.userId) throw new AppError(401, 'No autenticado');
  const isStaff = await isPlatformStaff(req.user.userId);
  if (!isStaff) throw new AppError(403, 'Acceso restringido a staff de plataforma');
}

/**
 * Stats de gestión de clientes.
 *
 * Query params:
 *   - `from` (YYYY-MM-DD): inicio del rango. Default: primer día del mes en curso.
 *   - `to`   (YYYY-MM-DD): fin del rango. Default: último día del mes en curso.
 */
export async function getStats(req: Request, res: Response, next: NextFunction) {
  try {
    await requireStaff(req);
    const now = new Date();
    const defaultFrom = new Date(now.getFullYear(), now.getMonth(), 1);
    const defaultTo = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);

    const fromStr = String(req.query.from || '').trim();
    const toStr = String(req.query.to || '').trim();
    const from = fromStr ? new Date(fromStr + 'T00:00:00') : defaultFrom;
    const to = toStr ? new Date(toStr + 'T23:59:59.999') : defaultTo;
    if (isNaN(from.getTime()) || isNaN(to.getTime())) {
      return next(new AppError(400, 'Rango de fechas inválido'));
    }
    const stats = await svc.getClientesStats({ from, to });
    return res.json(stats);
  } catch (err) { return next(err); }
}

export async function listUsuarios(req: Request, res: Response, next: NextFunction) {
  try {
    await requireStaff(req);
    const tenantId = String(req.params.tenantId || '');
    if (!tenantId) return next(new AppError(400, 'tenantId requerido'));
    const usuarios = await svc.getTenantUsuarios(tenantId);
    return res.json({ data: usuarios });
  } catch (err) { return next(err); }
}
