import { DataCaptureMethod } from "@komi-app/components";
import { DataCaptureFormField } from "./CreationModalForms/schemas";

import { DataCaptureField } from "@komi-app/shared-types"

/**
 * A method comprises of one primary ( compulsory) field
 * and one or more additional details field.
 * Given the UI, the objects are stored in 2 arrays and joined here.
 * @param contactMethods Contains the primary Fields
 * @param additionalContactMethods Contains the secondary fields
 * @returns
 */
export const cleanAndAggregateMethods = function (
  contactMethods: DataCaptureMethod[],
  additionalContactMethods: DataCaptureFormField[],
  talentName?: string
): DataCaptureMethod[] {
  const aggregatedMethod: DataCaptureMethod[] = [];

  additionalContactMethods.forEach((method, index) => {
    method.orderIndex = index + 1; // +1 because the 0th index is always the primary field
  });

  contactMethods.forEach((method, index) => {
    const allFields = [];
    method.talentName = `${talentName}`;
    const primaryField = method.fields.filter(
      (method) => method.name == "email" || method.name == "phone"
    ) as unknown as DataCaptureFormField[];

    allFields.push(...primaryField, ...additionalContactMethods);
    const updatedMethod = { ...method, fields: allFields };
    aggregatedMethod.push(updatedMethod);
  });

  return aggregatedMethod;
};

export const spreadMethods = function (methods: DataCaptureMethod[]): {
  contactMethods: DataCaptureMethod[];
  additionalContactMethods: DataCaptureFormField[];
} {
  const contactMethods: DataCaptureMethod[] = [];
  let additionalContactMethods: DataCaptureFormField[] = [];
  methods.forEach((method: DataCaptureMethod) => {
    additionalContactMethods = method.fields.filter(
      (field) =>
        field.type !== DataCaptureField.EMAIL &&
        field.type !== DataCaptureField.PHONE_NUMBER
    );

    const singleField = method.fields.filter(
      (field) =>
        field.type === DataCaptureField.EMAIL ||
        field.type === DataCaptureField.PHONE_NUMBER
    );

    contactMethods.push({ ...method, fields: singleField });
  });
  return { contactMethods, additionalContactMethods };
};
