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

export default defineEventHandler(async (event) => {
  try {
    // Get template ID from route parameters
    const templateId = getRouterParam(event, "id");

    if (!templateId) {
      throw createError({
        statusCode: 400,
        statusMessage: "Template ID is required",
      });
    }

    console.log("Deleting template:", templateId);

    // Get current user (assuming auth middleware provides this)
    const user = event.context.user;
    if (!user || !user.userID) {
      throw createError({
        statusCode: 401,
        statusMessage: "Authentication required",
      });
    }

    // Check if template exists and user has permission
    const existingTemplate = await prisma.notification_templates.findFirst({
      where: {
        id: templateId,
        // Optionally restrict to user's own templates
        // created_by: user.userID.toString()
      }
    });

    if (!existingTemplate) {
      throw createError({
        statusCode: 404,
        statusMessage: "Template not found or you don't have permission to delete it",
      });
    }

    // Check if template is being used by any notifications
    const templatesInUse = await prisma.notifications.findFirst({
      where: {
        template_id: templateId
      }
    });

    if (templatesInUse) {
      throw createError({
        statusCode: 400,
        statusMessage: "Cannot delete template that is currently being used by notifications. Please remove it from notifications first.",
      });
    }

    console.log("Template found and can be deleted:", existingTemplate.name);

    // Delete the template
    await prisma.notification_templates.delete({
      where: {
        id: templateId
      }
    });

    console.log("Template deleted successfully:", templateId);

    // Return success response
    return {
      success: true,
      data: {
        message: `Template "${existingTemplate.name}" has been deleted successfully`,
        deletedTemplate: {
          id: existingTemplate.id,
          name: existingTemplate.name,
          value: existingTemplate.value
        }
      }
    };

  } catch (error) {
    console.error("Template deletion error:", error);
    console.error("Error details:", {
      message: error.message,
      stack: error.stack,
      cause: error.cause,
      code: error.code,
      statusCode: error.statusCode
    });

    // Handle Prisma errors
    if (error.code && error.code.startsWith('P')) {
      console.error("Prisma error code:", error.code);
      
      if (error.code === 'P2025') {
        throw createError({
          statusCode: 404,
          statusMessage: "Template not found",
          data: {
            error: "The template you're trying to delete does not exist.",
            code: error.code
          }
        });
      }
      
      throw createError({
        statusCode: 400,
        statusMessage: "Database operation failed",
        data: {
          error: error.message,
          code: error.code
        }
      });
    }

    // Handle known errors with status codes
    if (error.statusCode) {
      throw error;
    }

    // Generic server error
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to delete template",
      data: {
        error: error.message
      }
    });
  } finally {
  }
}); 