import { z } from 'zod';
import prisma from "~/server/utils/prisma";

const settingsSchema = z.object({
  autoRetry: z.boolean(),
  enableFallback: z.boolean(),
  maxRetries: z.number().int().min(0).max(5),
  retryDelay: z.number().int().min(1).max(300),
  priority: z.enum(['low', 'normal', 'high']),
  enableReports: z.boolean()
});

export default defineEventHandler(async (event) => {
  try {
    // Get current user from auth middleware
    const user = event.context.user;
    if (!user) {
      throw createError({
        statusCode: 401,
        statusMessage: "Authentication required",
      });
    }

    // Validate request body
    const body = await readValidatedBody(event, settingsSchema.parse);

    // Update or create delivery settings
    const settings = await prisma.notification_delivery_settings.upsert({
      where: {
        id: 1 // Only one settings record
      },
      update: {
        auto_retry: body.autoRetry,
        enable_fallback: body.enableFallback,
        max_retries: body.maxRetries,
        retry_delay: body.retryDelay,
        priority: body.priority,
        enable_reports: body.enableReports,
        updated_at: new Date(),
        updated_by: user.id
      },
      create: {
        id: 1,
        auto_retry: body.autoRetry,
        enable_fallback: body.enableFallback,
        max_retries: body.maxRetries,
        retry_delay: body.retryDelay,
        priority: body.priority,
        enable_reports: body.enableReports,
        created_by: user.id,
        updated_by: user.id
      }
    });

    return {
      success: true,
      data: {
        autoRetry: settings.auto_retry,
        enableFallback: settings.enable_fallback,
        maxRetries: settings.max_retries,
        retryDelay: settings.retry_delay,
        priority: settings.priority,
        enableReports: settings.enable_reports
      }
    };
  } catch (error) {
    console.error('Error updating delivery settings:', error);
    
    if (error instanceof z.ZodError) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Invalid request data',
        data: error.errors
      });
    }
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to update delivery settings'
    });
  } finally {
  }
}); 