import { d as defaultHandler } from "./defaultHandler-yvm7aMmf.js";
import client from "@sendgrid/client";
import { l as logger, j as symmetricDecrypt } from "./user--mpkKOwW.js";
import { H as HttpError } from "./http-error-RJXCPZV2.js";
import { d as defaultResponder } from "./defaultResponder-GZldAmhY.js";
import { c as checkSession } from "./auth-_2QcUxTs.js";
import z__default from "zod";
const add = defaultHandler({
  GET: import("./_getAdd-KxfmQZSz.js"),
  POST: import("./_postAdd-fi5snjMY.js")
});
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 = 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({ statusCode: 400, message: "No Api Key provoided to check" });
  checkSession(req);
  const sendgrid = new Sendgrid(api_key);
  try {
    const usernameInfo = await sendgrid.username();
    if (usernameInfo.username) {
      return {};
    } else {
      throw new HttpError({ statusCode: 404 });
    }
  } catch (e) {
    throw new HttpError({ statusCode: 500, message: e });
  }
}
const check = defaultHandler({
  POST: Promise.resolve({ default: defaultResponder(getHandler) })
});
const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  add,
  check
}, Symbol.toStringTag, { value: "Module" }));
const apiKeySchema = z__default.object({
  encrypted: z__default.string()
});
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
class CloseComCalendarService {
  constructor(credential) {
    this.integrationName = "";
    this.integrationName = "sendgrid_other_calendar";
    this.log = logger.getSubLogger({ prefix: [`[[lib] ${this.integrationName}`] });
    const parsedCredentialKey = apiKeySchema.safeParse(credential.key);
    let decrypted;
    if (parsedCredentialKey.success) {
      decrypted = 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" }));
export {
  index$1 as api,
  index as lib
};
