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

    // Generate new version number (increment current version)
    const currentVersion = template.version || "1.0";
    const versionParts = currentVersion.split('.');
    const majorVersion = parseInt(versionParts[0]) || 1;
    const minorVersion = parseInt(versionParts[1]) || 0;
    const newVersion = `${majorVersion}.${minorVersion + 1}`;

    // Create version history entry for current template state before restore
    await prisma.notification_template_versions.create({
      data: {
        template_id: templateId,
        version: currentVersion,
        name: template.name,
        description: template.description,
        subject: template.subject,
        preheader: template.preheader,
        email_content: template.email_content,
        push_title: template.push_title,
        push_body: template.push_body,
        push_icon: template.push_icon,
        push_url: template.push_url,
        sms_content: template.sms_content,
        category: template.category,
        channels: template.channels,
        status: template.status,
        tags: template.tags,
        is_personal: template.is_personal,
        from_name: template.from_name,
        reply_to: template.reply_to,
        track_opens: template.track_opens,
        variables: template.variables,
        is_active: template.is_active,
        change_description: `Automatic backup before restoring version ${version.version}`,
        is_current: false,
        created_by: user.userID.toString(),
      }
    });

    // Update the current template with the version data
    const updatedTemplate = await prisma.notification_templates.update({
      where: { id: templateId },
      data: {
        name: version.name,
        description: version.description,
        subject: version.subject,
        preheader: version.preheader,
        email_content: version.email_content,
        push_title: version.push_title,
        push_body: version.push_body,
        push_icon: version.push_icon,
        push_url: version.push_url,
        sms_content: version.sms_content,
        category: version.category,
        channels: version.channels,
        status: version.status,
        tags: version.tags,
        is_personal: version.is_personal,
        from_name: version.from_name,
        reply_to: version.reply_to,
        track_opens: version.track_opens,
        variables: version.variables,
        is_active: version.is_active,
        version: newVersion,
        updated_by: user.userID.toString(),
        updated_at: new Date(),
      }
    });

    // Create version history entry for the restored version
    await prisma.notification_template_versions.create({
      data: {
        template_id: templateId,
        version: newVersion,
        name: version.name,
        description: version.description,
        subject: version.subject,
        preheader: version.preheader,
        email_content: version.email_content,
        push_title: version.push_title,
        push_body: version.push_body,
        push_icon: version.push_icon,
        push_url: version.push_url,
        sms_content: version.sms_content,
        category: version.category,
        channels: version.channels,
        status: version.status,
        tags: version.tags,
        is_personal: version.is_personal,
        from_name: version.from_name,
        reply_to: version.reply_to,
        track_opens: version.track_opens,
        variables: version.variables,
        is_active: version.is_active,
        change_description: `Restored from version ${version.version}`,
        is_current: true,
        created_by: user.userID.toString(),
      }
    });

    // Mark previous current version as not current
    await prisma.notification_template_versions.updateMany({
      where: {
        template_id: templateId,
        is_current: true,
        version: { not: newVersion }
      },
      data: {
        is_current: false
      }
    });

    console.log(`Version ${version.version} restored successfully as version ${newVersion}`);

    // Return success response
    return {
      success: true,
      data: {
        message: `Version ${version.version} has been restored successfully as version ${newVersion}`,
        templateId,
        restoredVersion: version.version,
        newVersion,
        template: {
          id: updatedTemplate.id,
          title: updatedTemplate.name,
          version: updatedTemplate.version,
          updatedAt: updatedTemplate.updated_at
        }
      }
    };

  } catch (error) {
    console.error("Version restore 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 restore version",
      data: {
        error: error.message
      }
    });
  } finally {
  }
}); 