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

    // Fetch the template
    const template = await prisma.notification_templates.findUnique({
      where: {
        id: templateId,
      },
    });

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

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

    // Format the response data to match frontend expectations
    const formattedTemplate = {
      id: template.id,
      title: template.name,
      value: template.value,
      description: template.description || "",
      subject: template.subject || "",
      preheader: template.preheader || "",
      category: template.category || "",
      channels: template.channels || [],
      status: template.status || "Draft",
      version: template.version || "1.0",
      content: template.email_content || "",
      tags: template.tags || "",
      isPersonal: template.is_personal || false,
      // Email specific settings
      fromName: template.from_name || "",
      replyTo: template.reply_to || "",
      trackOpens: template.track_opens !== false, // Default to true
      // Push notification specific settings
      pushTitle: template.push_title || "",
      pushIcon: template.push_icon || "",
      pushUrl: template.push_url || "",
      // SMS specific settings
      smsContent: template.sms_content || "",
      // Metadata
      isActive: template.is_active || false,
      variables: template.variables || null,
      createdBy: template.created_by,
      updatedBy: template.updated_by,
      createdAt: template.created_at,
      updatedAt: template.updated_at,
    };

    // Return success response
    return {
      success: true,
      message: "wowowowow",
      data: {
        template: formattedTemplate,
      },
    };
  } catch (error) {
    console.error("Template 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 template",
      data: {
        error: error.message,
      },
    });
  } finally {
  }
});
