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

const pushConfigSchema = 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;
    if (!user) {
      throw createError({
        statusCode: 401,
        statusMessage: "Authentication required",
      });
    }

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

    // Update or create push notification configuration
    const pushConfig = await prisma.notification_delivery_config.upsert({
      where: {
        channel_type: 'push'
      },
      update: {
        is_enabled: body.enabled,
        provider: body.provider,
        provider_config: body.config || {},
        status: body.enabled ? 'Connected' : 'Disabled',
        updated_at: new Date(),
        updated_by: user.id
      },
      create: {
        channel_type: 'push',
        is_enabled: body.enabled,
        provider: body.provider,
        provider_config: body.config || {},
        status: body.enabled ? 'Connected' : 'Disabled',
        success_rate: 0,
        created_by: user.id,
        updated_by: user.id
      }
    });

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