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

// Helper function to map is_active integer to status string
function getStatusFromIsActive(isActive) {
  console.log("Converting is_active value:", isActive, "type:", typeof isActive);
  switch (isActive) {
    case 1:
      return "Active";
    case 0:
      return "Inactive";
    case 2:
      return "Draft";
    default:
      return "Draft";
  }
}

export default defineEventHandler(async (event) => {
  try {
    // Use raw query to get the actual integer values for is_active
    const templates = await prisma.$queryRaw`
      SELECT
        id,
        name,
        value,
        category,
        is_active,
        created_at,
        updated_at
      FROM notification_templates
      ORDER BY name ASC
    `;

    console.log("RAW QUERY TEMPLATES:", templates);
    console.log("First template is_active:", templates[0]?.is_active, "type:", typeof templates[0]?.is_active);

    // Format the response to match frontend expectations
    return {
      success: true,
      message: "Code: A1",
      data: {
        templates: templates.map((template) => ({
          id: template.id,
          title: template.name,
          value: template.value,
          category: template.category || "General",
          is_active: template.is_active,
          created_at: template.created_at || "",
          updated_at: template.updated_at || "",
        })),
      },
    };
  } catch (error) {
    console.error("Error fetching templates:", error);
    return {
      success: false,
      data: {
        message: "Failed to fetch templates",
        error: error.message,
      },
    };
  } finally {
  }
});
