import prisma from "~/server/utils/prisma";

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",
      });
    }

    // Get all email provider configurations
    const emailConfigs = await prisma.notification_delivery_config.findMany({
      where: {
        channel_type: 'email'
      },
      select: {
        id: true,
        is_enabled: true,
        provider: true,
        provider_config: true,
        status: true,
        success_rate: true,
        created_at: true,
        updated_at: true
      }
    });

    if (!emailConfigs || emailConfigs.length === 0) {
      return {
        success: true,
        data: {
          providers: [],
          activeProvider: null
        }
      };
    }

    // Convert to provider-keyed object
    const providersData = {};
    emailConfigs.forEach(config => {
      providersData[config.provider.toLowerCase().replace(/\s+/g, '-')] = {
        enabled: config.is_enabled,
        provider: config.provider,
        status: config.status,
        successRate: config.success_rate,
        config: config.provider_config
      };
    });

    // Find active provider (fallback to first enabled or first in list)
    const activeConfig = emailConfigs.find(c => c.is_enabled) || emailConfigs[0];

    return {
      success: true,
      data: {
        providers: providersData,
        activeProvider: activeConfig.provider.toLowerCase().replace(/\s+/g, '-'),
        // For backward compatibility
        enabled: activeConfig.is_enabled,
        provider: activeConfig.provider.toLowerCase().replace(/\s+/g, '-'),
        status: activeConfig.status,
        successRate: activeConfig.success_rate,
        config: activeConfig.provider_config
      }
    };
  } catch (error) {
    console.error('Error fetching email configuration:', error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Failed to fetch email configuration'
    });
  } finally {
  }
}); 