import type { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { AppError } from '../middlewares/error.middleware.js';
import {
  EMAIL_TYPES,
  getEmailPreferencesPorContribuyente,
  setContribuyenteEmailPreferences,
} from '../services/notification-preferences.service.js';

export async function listPreferences(req: Request, res: Response, next: NextFunction) {
  try {
    const data = await getEmailPreferencesPorContribuyente(req.tenantPool!);
    res.json({ emailTypes: EMAIL_TYPES, data });
  } catch (error) {
    next(error);
  }
}

const updateSchema = z.object({
  contribuyenteId: z.string().uuid(),
  preferences: z.record(z.string(), z.boolean()),
});

export async function updatePreferences(req: Request, res: Response, next: NextFunction) {
  try {
    const { contribuyenteId, preferences } = updateSchema.parse(req.body);
    const updated = await setContribuyenteEmailPreferences(req.tenantPool!, contribuyenteId, preferences);
    res.json({ contribuyenteId, preferences: updated });
  } catch (error) {
    if (error instanceof z.ZodError) return next(new AppError(400, error.errors[0].message));
    next(error);
  }
}
