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

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

    if (!templateId || !versionId) {
      throw createError({
        statusCode: 400,
        statusMessage: "Template ID and Version ID are required",
      });
    }

    console.log(`Deleting version ${versionId} for 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
    const template = await prisma.notification_templates.findUnique({
      where: { id: templateId }
    });

    if (!template) {
      throw createError({
        statusCode: 404,
        statusMessage: "Template not found",
      });
    }

    // Check if version exists
    const version = await prisma.notification_template_versions.findUnique({
      where: { id: versionId }
    });

    if (!version || version.template_id !== templateId) {
      throw createError({
        statusCode: 404,
        statusMessage: "Version not found",
      });
    }

    // Check if this is the current version
    if (version.is_current) {
      throw createError({
        statusCode: 400,
        statusMessage: "Cannot delete current version",
        data: {
          error: "You cannot delete the current version of a template. Please restore a different version first."
        }
      });
    }

    // Check if there are other versions (prevent deletion of the only version)
    const versionCount = await prisma.notification_template_versions.count({
      where: { template_id: templateId }
    });

    if (versionCount <= 1) {
      throw createError({
        statusCode: 400,
        statusMessage: "Cannot delete the only version",
        data: {
          error: "This is the only version of the template. At least one version must exist."
        }
      });
    }

    // Delete the version
    await prisma.notification_template_versions.delete({
      where: { id: versionId }
    });

    console.log(`Version ${version.version} deleted successfully`);

    // Return success response
    return {
      success: true,
      data: {
        message: `Version ${version.version} has been deleted successfully`,
        templateId,
        deletedVersion: version.version,
        deletedVersionId: versionId
      }
    };

  } catch (error) {
    console.error("Version delete 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 or version not found",
          data: {
            error: "The template or version you're looking for 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 version",
      data: {
        error: error.message
      }
    });
  } finally {
  }
}); 