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

// Helper function to generate unique value from title
function generateUniqueValue(title) {
  return title
    .toLowerCase()
    .replace(/[^a-z0-9\s]/g, '')
    .replace(/\s+/g, '_')
    .substring(0, 50);
}

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

    // Find the original template
    const originalTemplate = await prisma.notification_templates.findUnique({
      where: {
        id: templateId
      }
    });

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

    console.log("Original template found:", originalTemplate.name);

    // Generate new name and value for the duplicate
    const newName = `${originalTemplate.name} (Copy)`;
    let uniqueValue = generateUniqueValue(newName);
    
    // Check if value already exists and make it unique
    let counter = 1;
    let finalValue = uniqueValue;
    while (true) {
      const existingTemplate = await prisma.notification_templates.findUnique({
        where: { value: finalValue }
      });
      
      if (!existingTemplate) {
        break;
      }
      
      finalValue = `${uniqueValue}_copy_${counter}`;
      counter++;
      
      // Safety check to prevent infinite loop
      if (counter > 100) {
        finalValue = `${uniqueValue}_copy_${Date.now()}`;
        break;
      }
    }

    // Prepare duplicate template data
    const duplicateData = {
      name: newName,
      value: finalValue,
      description: originalTemplate.description,
      subject: originalTemplate.subject,
      preheader: originalTemplate.preheader,
      email_content: originalTemplate.email_content,
      push_title: originalTemplate.push_title,
      push_body: originalTemplate.push_body,
      push_icon: originalTemplate.push_icon,
      push_url: originalTemplate.push_url,
      sms_content: originalTemplate.sms_content,
      category: originalTemplate.category,
      channels: originalTemplate.channels,
      status: "Draft", // Always start as draft
      version: "1.0", // Reset version for new template
      tags: originalTemplate.tags,
      is_personal: originalTemplate.is_personal,
      from_name: originalTemplate.from_name,
      reply_to: originalTemplate.reply_to,
      track_opens: originalTemplate.track_opens,
      variables: originalTemplate.variables,
      is_active: false, // Inactive by default
      created_by: user.userID.toString(),
      updated_by: user.userID.toString(),
    };

    console.log("Creating duplicate with data:", duplicateData);

    // Create the duplicate template
    const duplicateTemplate = await prisma.notification_templates.create({
      data: duplicateData
    });

    console.log("Template duplicated successfully:", duplicateTemplate.id);

    // Return success response
    return {
      success: true,
      data: {
        message: `Template "${originalTemplate.name}" has been duplicated successfully`,
        originalTemplate: {
          id: originalTemplate.id,
          name: originalTemplate.name,
          value: originalTemplate.value
        },
        duplicateTemplate: {
          id: duplicateTemplate.id,
          name: duplicateTemplate.name,
          value: duplicateTemplate.value,
          status: duplicateTemplate.status,
          version: duplicateTemplate.version,
          created_at: duplicateTemplate.created_at
        }
      }
    };

  } catch (error) {
    console.error("Template duplication 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 === 'P2002') {
        throw createError({
          statusCode: 400,
          statusMessage: "Duplicate value conflict",
          data: {
            error: "Unable to generate unique identifier for the duplicate template. Please try again.",
            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 duplicate template",
      data: {
        error: error.message
      }
    });
  } finally {
  }
}); 