import type { Request, Response, NextFunction } from 'express';
import * as regimenService from '../services/regimen.service.js';

/** Resuelve el tenantId efectivo (impersonación o propio) */
function effectiveTenantId(req: Request): string {
  return req.viewingTenantId || req.user!.tenantId;
}

export async function getAllRegimenes(req: Request, res: Response, next: NextFunction) {
  try {
    const regimenes = await regimenService.getAllRegimenes();
    res.json(regimenes);
  } catch (error) {
    next(error);
  }
}

export async function getActivos(req: Request, res: Response, next: NextFunction) {
  try {
    const activos = await regimenService.getRegimenesActivos(effectiveTenantId(req));
    res.json(activos);
  } catch (error) {
    next(error);
  }
}

export async function setActivos(req: Request, res: Response, next: NextFunction) {
  try {
    if (req.user!.role !== 'owner') {
      return res.status(403).json({ message: 'Solo el dueño puede configurar regímenes' });
    }

    const { regimenIds } = req.body;
    if (!Array.isArray(regimenIds)) {
      return res.status(400).json({ message: 'regimenIds debe ser un array' });
    }

    const result = await regimenService.setRegimenesActivos(effectiveTenantId(req), regimenIds);
    res.json(result);
  } catch (error) {
    next(error);
  }
}

export async function getIgnorados(req: Request, res: Response, next: NextFunction) {
  try {
    const ignorados = await regimenService.getRegimenesIgnorados(effectiveTenantId(req));
    res.json(ignorados);
  } catch (error) {
    next(error);
  }
}

export async function setIgnorados(req: Request, res: Response, next: NextFunction) {
  try {
    if (req.user!.role !== 'owner') {
      return res.status(403).json({ message: 'Solo el dueño puede configurar regímenes' });
    }

    const { regimenIds } = req.body;
    if (!Array.isArray(regimenIds)) {
      return res.status(400).json({ message: 'regimenIds debe ser un array' });
    }

    const result = await regimenService.setRegimenesIgnorados(effectiveTenantId(req), regimenIds);
    res.json(result);
  } catch (error) {
    next(error);
  }
}
