"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const defaultHandler = require("./defaultHandler-MSjhitc-.cjs");
const client = require("@sendgrid/client");
const index$2 = require("./index-QSf6WJj0.cjs");
const httpError = require("./http-error-mkY8Ke7V.cjs");
const defaultResponder = require("./defaultResponder-ZNP4idbH.cjs");
const auth = require("./auth--eKdiWSi.cjs");
const z = require("zod");
const add = defaultHandler.defaultHandler({
  GET: Promise.resolve().then(() => require("./_getAdd-P--ZzhF2.cjs")),
  POST: Promise.resolve().then(() => require("./_postAdd-6FIAvCJ5.cjs"))
});
const environmentApiKey = process.env.SENDGRID_SYNC_API_KEY || "";
class Sendgrid {
  constructor(providedApiKey = "") {
    this.username = async () => {
      const username = await this.sendgridRequest({
        url: `/v3/user/username`,
        method: "GET"
      });
      return username;
    };
    this.log = index$2.logger.getSubLogger({ prefix: [`[[lib] sendgrid`] });
    if (!providedApiKey && !environmentApiKey)
      throw Error("Sendgrid Api Key not present");
    client.setApiKey(providedApiKey || environmentApiKey);
  }
  async sendgridRequest(data) {
    this.log.debug("sendgridRequest:request", data);
    const results = await client.request(data);
    this.log.debug("sendgridRequest:results", results);
    if (results[1].errors)
      throw Error(`Sendgrid request error: ${results[1].errors}`);
    return results[1];
  }
  async getSendgridContactId(email) {
    const search = await this.sendgridRequest({
      url: `/v3/marketing/contacts/search`,
      method: "POST",
      body: {
        query: `email LIKE '${email}'`
      }
    });
    this.log.debug("sync:sendgrid:getSendgridContactId:search", search);
    return search.result || [];
  }
  async getSendgridCustomFieldsIds(customFields) {
    const allFields = await this.sendgridRequest({
      url: `/v3/marketing/field_definitions`,
      method: "GET"
    });
    allFields.custom_fields = allFields.custom_fields ?? [];
    this.log.debug("sync:sendgrid:getCustomFieldsIds:allFields", allFields);
    const customFieldsNames = allFields.custom_fields.map((fie) => fie.name);
    this.log.debug("sync:sendgrid:getCustomFieldsIds:customFieldsNames", customFieldsNames);
    const customFieldsExist = customFields.map((cusFie) => customFieldsNames.includes(cusFie[0]));
    this.log.debug("sync:sendgrid:getCustomFieldsIds:customFieldsExist", customFieldsExist);
    return await Promise.all(
      customFieldsExist.map(async (exist, idx) => {
        if (!exist) {
          const [name, field_type] = customFields[idx];
          const created = await this.sendgridRequest({
            url: `/v3/marketing/field_definitions`,
            method: "POST",
            body: {
              name,
              field_type
            }
          });
          this.log.debug("sync:sendgrid:getCustomFieldsIds:customField:created", created);
          return created.id;
        } else {
          const index2 = customFieldsNames.findIndex((val) => val === customFields[idx][0]);
          if (index2 >= 0) {
            this.log.debug(
              "sync:sendgrid:getCustomFieldsIds:customField:existed",
              allFields.custom_fields[index2].id
            );
            return allFields.custom_fields[index2].id;
          } else {
            throw Error("Couldn't find the field index");
          }
        }
      })
    );
  }
}
async function getHandler(req) {
  const { api_key } = req.body;
  if (!api_key)
    throw new httpError.HttpError({ statusCode: 400, message: "No Api Key provoided to check" });
  auth.checkSession(req);
  const sendgrid = new Sendgrid(api_key);
  try {
    const usernameInfo = await sendgrid.username();
    if (usernameInfo.username) {
      return {};
    } else {
      throw new httpError.HttpError({ statusCode: 404 });
    }
  } catch (e) {
    throw new httpError.HttpError({ statusCode: 500, message: e });
  }
}
const check = defaultHandler.defaultHandler({
  POST: Promise.resolve({ default: defaultResponder.defaultResponder(getHandler) })
});
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  check
}, Symbol.toStringTag, { value: "Module" }));
const apiKeySchema = z.object({
  encrypted: z.string()
});
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
class CloseComCalendarService {
  constructor(credential) {
    this.integrationName = "";
    this.integrationName = "sendgrid_other_calendar";
    this.log = index$2.logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
    const parsedCredentialKey = apiKeySchema.safeParse(credential.key);
    let decrypted;
    if (parsedCredentialKey.success) {
      decrypted = index$2.symmetricDecrypt(parsedCredentialKey.data.encrypted, CALENDSO_ENCRYPTION_KEY);
      const { api_key } = JSON.parse(decrypted);
      this.sendgrid = new Sendgrid(api_key);
    } else {
      throw Error(
        `No API Key found for userId ${credential.userId} and appId ${credential.appId}: ${parsedCredentialKey.error}`
      );
    }
  }
  async createEvent(event) {
    const contactsData = event.attendees.map((attendee) => ({
      first_name: attendee.name,
      email: attendee.email
    }));
    const result = await this.sendgrid.sendgridRequest({
      url: `/v3/marketing/contacts`,
      method: "PUT",
      body: {
        contacts: contactsData
      }
    });
    return Promise.resolve({
      id: "",
      uid: result.job_id,
      password: "",
      url: "",
      type: this.integrationName,
      additionalInfo: {
        result
      }
    });
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async updateEvent(_uid, _event) {
    return Promise.resolve();
  }
  async deleteEvent(_uid) {
    return Promise.resolve();
  }
  async getAvailability(_dateFrom, _dateTo, _selectedCalendars) {
    return Promise.resolve([]);
  }
  async listCalendars(_event) {
    return Promise.resolve([]);
  }
}
const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CalendarService: CloseComCalendarService
}, Symbol.toStringTag, { value: "Module" }));
exports.api = index$1;
exports.lib = index;
