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

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

export default defineEventHandler(async (event) => {
  try {
    const user = event.context.user;
    if (!user) {
      throw createError({
        statusCode: 401,
        statusMessage: "Authentication required",
      });
    }
    const body = await readValidatedBody(event, smsConfigSchema.parse);
    const smsConfig = await prisma.notification_delivery_config.upsert({
      where: { channel_type: 'sms' },
      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: 'sms',
        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: smsConfig.is_enabled,
        provider: smsConfig.provider,
        status: smsConfig.status,
        successRate: smsConfig.success_rate,
        config: smsConfig.provider_config
      }
    };
  } catch (error) {
    console.error('Error updating SMS 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 SMS configuration'
    });
  } finally {
  }
}); 