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("Fetching version history 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 the version history table exists
    let versions = [];
    try {
      // Fetch version history for the template
      versions = await prisma.notification_template_versions.findMany({
        where: {
          template_id: templateId
        },
        orderBy: {
          created_at: 'desc'
        }
      });
    } catch (dbError) {
      console.error("Database error when fetching versions:", dbError);
      
      // If table doesn't exist, return empty array
      if (dbError.code === 'P2021' || dbError.message.includes('doesn\'t exist')) {
        console.log("Version history table doesn't exist, returning empty array");
        versions = [];
      } else {
        throw dbError;
      }
    }

    // Format the response data
    const formattedVersions = versions.map(version => ({
      id: version.id,
      version: version.version,
      name: version.name,
      description: version.description,
      subject: version.subject,
      content: version.email_content,
      changeDescription: version.change_description,
      isCurrent: version.is_current,
      status: version.status,
      createdBy: version.created_by,
      createdAt: version.created_at,
      formattedCreatedAt: version.created_at 
        ? new Date(version.created_at).toLocaleDateString("en-US", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
          })
        : "",
    }));

    console.log(`Found ${formattedVersions.length} versions for template ${templateId}`);

    // Return success response
    return {
      success: true,
      data: {
        templateId,
        templateName: template.name,
        versions: formattedVersions,
        totalCount: formattedVersions.length
      }
    };

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