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

const emailConfigSchema = z.object({
  enabled: z.boolean(),
  provider: z.string(),
  config: z.record(z.any()).optional()
});

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

    // Validate request body
    const body = emailConfigSchema.parse(await readBody(event));

    // Normalize provider name for database lookup
    const providerName = body.provider === 'mailtrap' ? 'Mailtrap' :
                         body.provider === 'aws-ses' ? 'AWS SES' :
                         body.provider;

    // If enabling this provider, disable all others for this channel
    if (body.enabled) {
      await prisma.notification_delivery_config.updateMany({
        where: {
          channel_type: 'email',
          provider: { not: providerName }
        },
        data: {
          is_enabled: false,
          updated_at: now,
          updated_by: userId
        }
      });
    }

    // Check if config already exists for this provider
    const existingConfig = await prisma.notification_delivery_config.findFirst({
      where: {
        channel_type: 'email',
        provider: providerName
      }
    });

    let emailConfig;
    if (existingConfig) {
      // Update existing config
      emailConfig = await prisma.notification_delivery_config.update({
        where: {
          id: existingConfig.id
        },
        data: {
          is_enabled: body.enabled,
          provider_config: body.config || {},
          status: body.enabled ? 'Connected' : 'Disabled',
          updated_at: now,
          updated_by: userId
        }
      });
    } else {
      // Create new config
      emailConfig = await prisma.notification_delivery_config.create({
        data: {
          channel_type: 'email',
          is_enabled: body.enabled,
          provider: providerName,
          provider_config: body.config || {},
          status: body.enabled ? 'Connected' : 'Disabled',
          success_rate: 0,
          created_by: userId,
          updated_by: userId,
          updated_at: now
        }
      });
    }

    return {
      success: true,
      data: {
        enabled: emailConfig.is_enabled,
        provider: emailConfig.provider,
        status: emailConfig.status,
        successRate: emailConfig.success_rate,
        config: emailConfig.provider_config
      }
    };
  } catch (error) {
    console.error('Error updating email configuration:', 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 email configuration'
    });
  } finally {
  }
}); 