import type { PrimariaGlobalStateManager } from "../global-state/global-state";
import { IEcapEvent } from "./typings";

export const LAST_WORKED_DIAGNOSTICS_KEY = "lastWorkedDiagnostics";

const EVENTS_WITH_DIAGNOSTICS = [
  "PROVES_ORDRES_CLINIQUES_CONSULTAR",
  "RESULT_OC",
  "LABORATORI_SEROTECA_PETICIO_CONSULTA",
  "ORDRE_TRACTAMENT",
  "PRESCRIPCIO_ACTIVA",
  "REV_IT",
  "OC_EXPRES",
] as const;

export abstract class EcapEventManager {
  /**
   * Publish an Ecap event.
   * @param eventType - Event type.
   * @param accio - Action.
   * @param payload - Additional payload properties.
   */
  abstract publish(eventType: string, accio: string, payload?: Record<string, unknown>): void;
}

class EcapEventManagerImpl implements EcapEventManager {
  constructor(private globalStateManager: PrimariaGlobalStateManager) {}

  publish(eventType: string, accio: string, payload?: Record<string, unknown>) {
    const ecapEvent = this.createEcapEvent(eventType, accio, payload ?? {});

    if (EVENTS_WITH_DIAGNOSTICS.includes(eventType as (typeof EVENTS_WITH_DIAGNOSTICS)[number])) {
      ecapEvent.DIAGNOSTICS = this.globalStateManager.getData<unknown[]>(LAST_WORKED_DIAGNOSTICS_KEY) ?? [];
    }

    this.raiseEcapEvent(ecapEvent);
  }

  private createEcapEvent(eventType: string, accio: string, payload: Record<string, unknown>) {
    return {
      TipusEvent: eventType,
      Accio: accio,
      ...payload,
    } as IEcapEvent;
  }
  private raiseEcapEvent(ecapEvent: IEcapEvent) {
    if (window.parent) window.parent.postMessage(JSON.stringify(ecapEvent), "*");
    console.log("method", JSON.stringify(ecapEvent));
  }
}

export const createEcapEventManager = (globalStateManager: PrimariaGlobalStateManager) =>
  new EcapEventManagerImpl(globalStateManager);
