var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var mailTemplates_exports = {};
__export(mailTemplates_exports, {
  mailComponentCount: () => mailComponentCount,
  mailRenderedTemplate: () => mailRenderedTemplate,
  mailTemplates: () => mailTemplates,
  resyncMailTemplate: () => resyncMailTemplate
});
module.exports = __toCommonJS(mailTemplates_exports);
var import_map = __toESM(require("@babel/runtime-corejs3/core-js/instance/map"));
var import_node_path = __toESM(require("node:path"));
var import_graphql_server = require("@cedarjs/graphql-server");
var import_project_config = require("@cedarjs/project-config");
var import_realtime = require("@cedarjs/realtime");
var import_db = require("../../lib/db");
var import_ast = require("../../util/ast");
var import_import = require("../../util/import");
var import_project = require("../../util/project");
const mailTemplates = async () => {
  return await import_db.db.mailTemplate.findMany({
    include: {
      components: true
    },
    orderBy: {
      name: "asc"
    }
  });
};
const resyncMailTemplate = async ({
  rawTemplateDistPath
}, ctx) => {
  const mailSrcPath = import_node_path.default.join((0, import_project.getUserProjectPaths)().api.src, "mail");
  const mailDistPath = import_node_path.default.join((0, import_project.getUserProjectPaths)().api.dist, "mail");
  const templateInProjectPathWithoutExtension = rawTemplateDistPath.substring(mailDistPath.length + 1, rawTemplateDistPath.length - 3);
  const templateSrcPath = (0, import_project_config.resolveFile)(import_node_path.default.resolve(import_node_path.default.join(mailSrcPath, templateInProjectPathWithoutExtension)));
  const templateName = templateInProjectPathWithoutExtension.split("/").pop() ?? templateInProjectPathWithoutExtension;
  let template = await import_db.db.mailTemplate.findUnique({
    where: {
      path: templateInProjectPathWithoutExtension
    }
  });
  if (!template) {
    template = await import_db.db.mailTemplate.create({
      data: {
        path: templateInProjectPathWithoutExtension,
        name: templateName
      }
    });
  }
  const components = (0, import_ast.extractMailComponents)(templateSrcPath);
  const upsertedIds = [];
  for (const component of components) {
    let componentInDb = await import_db.db.mailTemplateComponent.findFirst({
      where: {
        AND: [{
          name: component.name
        }, {
          mailTemplateId: template.id
        }]
      }
    });
    if (!componentInDb) {
      componentInDb = await import_db.db.mailTemplateComponent.create({
        data: {
          name: component.name,
          propsTemplate: component.props,
          mailTemplateId: template.id
        }
      });
    } else {
      await import_db.db.mailTemplateComponent.update({
        where: {
          id: componentInDb.id
        },
        data: {
          propsTemplate: component.props
        }
      });
    }
    upsertedIds.push(componentInDb.id);
  }
  await import_db.db.mailTemplateComponent.deleteMany({
    where: {
      AND: [{
        mailTemplateId: template.id
      }, {
        NOT: {
          id: {
            in: upsertedIds
          }
        }
      }]
    }
  });
  const filesInDist = (0, import_project.getFilesInDirectory)(mailDistPath);
  await import_db.db.mailTemplate.deleteMany({
    where: {
      NOT: {
        path: {
          in: (0, import_map.default)(filesInDist).call(filesInDist, (file) => file.substring(mailDistPath.length + 1, file.length - 3))
        }
      }
    }
  });
  const lqs = ctx?.context?.liveQueryStore ?? import_realtime.liveQueryStore;
  await lqs?.invalidate("Query.mailTemplates");
  return true;
};
const mailRenderedTemplate = async ({
  templateId,
  componentId,
  rendererId,
  props
}) => {
  let propsJSON = {};
  try {
    propsJSON = JSON.parse(props);
  } catch (e) {
    throw new import_graphql_server.UserInputError(`Invalid props JSON`);
  }
  const template = await import_db.db.mailTemplate.findUnique({
    where: {
      id: templateId
    }
  });
  if (!template) {
    throw new import_graphql_server.UserInputError(`Could not find template with id ${templateId}`);
  }
  const component = await import_db.db.mailTemplateComponent.findFirst({
    where: {
      AND: [{
        id: componentId
      }, {
        mailTemplateId: template.id
      }]
    }
  });
  if (!component) {
    throw new import_graphql_server.UserInputError(`Could not find component with id ${componentId} for template ${templateId}`);
  }
  const renderer = await import_db.db.mailRenderer.findUnique({
    where: {
      id: rendererId
    }
  });
  if (!renderer) {
    throw new import_graphql_server.UserInputError(`Could not find renderer with id ${rendererId}`);
  }
  const templatePath = import_node_path.default.join((0, import_project.getUserProjectPaths)().api.dist, "mail", template.path + ".js");
  const importedTemplate = await (0, import_import.importFresh)(templatePath);
  const importedComponent = importedTemplate[component.name];
  if (!importedComponent) {
    throw new Error(`Could not find component ${component.name} in template ${template.name}`);
  }
  const mailer = await (0, import_project.getUserProjectMailer)();
  if (!mailer) {
    throw new Error(`Could not find mailer in project`);
  }
  let renderResult;
  try {
    renderResult = await mailer.renderers[renderer.key].render(
      importedComponent(propsJSON),
      {}
      // TODO: We need a way for the user to specify the render options
    );
  } catch (error) {
    throw new Error(`Error rendering template: ${error.message}`);
  }
  return {
    id: `${templateId}:${componentId}:${rendererId}`,
    props: propsJSON,
    html: renderResult.html,
    text: renderResult.text
  };
};
const mailComponentCount = async () => {
  return await import_db.db.mailTemplateComponent.count();
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  mailComponentCount,
  mailRenderedTemplate,
  mailTemplates,
  resyncMailTemplate
});
//# sourceMappingURL=mailTemplates.js.map
