import { Request, Response, NextFunction } from 'express'; import * as tenantsService from '../services/tenants.service.js'; import { AppError } from '../utils/errors.js'; export async function getAllTenants(req: Request, res: Response, next: NextFunction) { try { // Only admin can list all tenants if (req.user!.role !== 'admin') { throw new AppError(403, 'Solo administradores pueden ver todos los clientes'); } const tenants = await tenantsService.getAllTenants(); res.json(tenants); } catch (error) { next(error); } } export async function getTenant(req: Request, res: Response, next: NextFunction) { try { if (req.user!.role !== 'admin') { throw new AppError(403, 'Solo administradores pueden ver detalles de clientes'); } const tenant = await tenantsService.getTenantById(String(req.params.id)); if (!tenant) { throw new AppError(404, 'Cliente no encontrado'); } res.json(tenant); } catch (error) { next(error); } } export async function createTenant(req: Request, res: Response, next: NextFunction) { try { if (req.user!.role !== 'admin') { throw new AppError(403, 'Solo administradores pueden crear clientes'); } const { nombre, rfc, plan, cfdiLimit, usersLimit } = req.body; if (!nombre || !rfc) { throw new AppError(400, 'Nombre y RFC son requeridos'); } const tenant = await tenantsService.createTenant({ nombre, rfc, plan, cfdiLimit, usersLimit, }); res.status(201).json(tenant); } catch (error) { next(error); } } export async function updateTenant(req: Request, res: Response, next: NextFunction) { try { if (req.user!.role !== 'admin') { throw new AppError(403, 'Solo administradores pueden editar clientes'); } const id = String(req.params.id); const { nombre, rfc, plan, cfdiLimit, usersLimit, active } = req.body; const tenant = await tenantsService.updateTenant(id, { nombre, rfc, plan, cfdiLimit, usersLimit, active, }); res.json(tenant); } catch (error) { next(error); } } export async function deleteTenant(req: Request, res: Response, next: NextFunction) { try { if (req.user!.role !== 'admin') { throw new AppError(403, 'Solo administradores pueden eliminar clientes'); } await tenantsService.deleteTenant(String(req.params.id)); res.status(204).send(); } catch (error) { next(error); } }