import type { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { AppError } from '../middlewares/error.middleware.js';
import {
  EMAIL_TYPES,
  NOTIFICATION_ROLES,
  getRoleEmailPreferences,
  setRoleEmailPreference,
  type EmailType,
  type NotificationRole,
} from '../services/notification-preferences.service.js';

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

const updateSchema = z.object({
  emailType: z.enum([...EMAIL_TYPES] as [string, ...string[]]),
  role: z.enum([...NOTIFICATION_ROLES] as [string, ...string[]]),
  enabled: z.boolean(),
});

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