import { createHash } from "crypto";
import app from "../../linkedin_ads.app.mjs";
export default {
  key: "linkedin_ads-send-conversion-event",
  name: "Send Conversion Event",
  description: "Sends a conversion event to LinkedIn Ads. [See the documentation](https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/conversions-api?view=li-lms-2024-01&tabs=http#streaming-conversion-events)",
  version: "0.0.6",
  annotations: {
    destructiveHint: false,
    openWorldHint: true,
    readOnlyHint: false,
  },
  type: "action",
  props: {
    app,
    adAccountId: {
      propDefinition: [
        app,
        "adAccountId",
      ],
    },
    conversionId: {
      propDefinition: [
        app,
        "conversionId",
        ({ adAccountId }) => ({
          adAccountId,
        }),
      ],
    },
    conversionHappenedAt: {
      type: "string",
      label: "Conversion Happened At",
      description: "Epoch timestamp in milliseconds at which the conversion event happened. Note: If your source records conversion timestamp in seconds, please insert 000 at the end to transform it to milliseconds. Eg. `1590739275000`.",
    },
    email: {
      type: "string",
      label: "Email",
      description: "Email address of the contact associated with the conversion event which needs to be in SHA256 format, a HEX encoded string with a maximum length of 64 characters. Eg. `test@example.com`.",
    },
    firstName: {
      type: "string",
      label: "First Name",
      description: "The first name of the contact to match the conversion.",
    },
    lastName: {
      type: "string",
      label: "Last Name",
      description: "The last name of the contact to match the conversion.",
    },
    conversionValueCurrencyCode: {
      type: "string",
      label: "Conversion Value Currency Code",
      description: "The currency code of the conversion value in ISO format. Eg. `USD`.",
    },
    conversionValueAmount: {
      type: "string",
      label: "Conversion Value Amount",
      description: "The value of the conversion in decimal string. If you set this field, you must also set in the **Conversion Value Currency Code** field. Eg. `100.05`.",
    },
    companyName: {
      type: "string",
      label: "Company Name",
      description: "A plain text string representing the company of the contact to match.",
      optional: true,
    },
    title: {
      type: "string",
      label: "Title",
      description: "A plain text string representing the title name of the contact to match. Eg. `Software Engineer`.",
      optional: true,
    },
    countryCode: {
      type: "string",
      label: "Country Code",
      description: "An ISO standardized [two letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) representing the country of the contact to match. Eg. `US`.",
      optional: true,
    },
    eventId: {
      type: "string",
      label: "Event ID",
      description: "The unique id generated by advertisers to indicate each event. This field is used for [deduplication](https://learn.microsoft.com/en-us/linkedin/marketing/conversions/deduplication?view=li-lms-2024-01).",
      optional: true,
    },
  },
  methods: {
    emailToSha256(email) {
      return createHash("sha256")
        .update(email)
        .digest("hex");
    },
    sendConversionEvent(args = {}) {
      return this.app._makeRequest({
        debug: true,
        method: "POST",
        path: "/conversionEvents",
        ...args,
      });
    },
  },
  async run({ $ }) {
    const {
      app,
      emailToSha256,
      sendConversionEvent,
      conversionId,
      conversionHappenedAt,
      conversionValueCurrencyCode,
      conversionValueAmount,
      email,
      firstName,
      lastName,
      companyName,
      title,
      countryCode,
      eventId,
    } = this;
    await sendConversionEvent({
      $,
      data: {
        conversion: app.getConversionUrn(conversionId),
        conversionHappenedAt: Number(conversionHappenedAt),
        conversionValue: {
          currencyCode: conversionValueCurrencyCode,
          amount: conversionValueAmount,
        },
        user: {
          userIds: [
            {
              idType: "SHA256_EMAIL",
              idValue: emailToSha256(email),
            },
          ],
          userInfo: {
            firstName,
            lastName,
            companyName,
            title,
            countryCode,
          },
        },
        eventId,
      },
    });
    $.export("$summary", "Successfully sent conversion event to LinkedIn Ads");
    return {
      success: true,
    };
  },
};