/**
 * Data Mapping Utilities for Create Guilds Form
 *
 * This module handles mapping data from three different sources:
 *
 * 1. EDIT MODE: Guild data passed directly as prop when editing existing guild
 *    - Handled by: getInitialValues() in formUtils.js
 *    - Data structure: guild object with nested user and address objects
 *
 * 2. DATABASE INQUIRY: Inquiry by national code returns data from our database
 *    - Handled by: extractFormFieldsFromDatabaseInquiry()
 *    - Condition: responseData.dbRegister === true
 *    - Data structure: responseData.user, responseData.guilds[] with nested address
 *
 * 3. EXTERNAL API INQUIRY: Inquiry by national code returns data from external system
 *    - Handled by: extractFormFieldsFromExternalApi()
 *    - Condition: responseData.dbRegister === false
 *    - Data structure: responseData.user, responseData.guilds[] with layerTwo object
 */

import { getRoleFromUrl } from "../../../../../utils/getRoleFromUrl";
import { normalizeExternalApiDate, normalizeDatabaseDate } from "./dateUtils";
import { formatDateForSubmit } from "./dateUtils";

/**
 * Prepares form data for submission to the API
 *
 * Three data sources can provide the initial data:
 * 1. Edit mode: Guild data passed as prop (guild parameter)
 * 2. Database inquiry: Inquiry returns data from our database (hasInquiry === false)
 * 3. External API inquiry: Inquiry returns data from external system (hasInquiry === true)
 *
 * @param {Object} values - Form values from Formik
 * @param {Object} guild - Guild data when editing existing guild (edit mode)
 * @param {string} originalPhoneNumber - Original phone number before edit
 * @param {boolean} hasInquiry - Whether data came from external API inquiry (true) or database (false)
 */
export const prepareSubmitData = (
  values,
  guild,
  originalPhoneNumber,
  hasInquiry
) => {
  const baseData = {
    national_id: values.national_id,
    mobile: values.mobile,
    mobilenumber: values.mobile,
    steward: !!values.steward,
    guild: !!values.guild,
    active_register_code: !!values.verify_mobile,
    firstName: values.first_name || "",
    lastName: values.last_name || "",
    fatherName: values.father_name || "",
    gender: values.gender || "",
    identityNo: values.national_code || "",
    isLive: values.is_alive === "بلی" || values.is_alive === true,
    birthDate: formatDateForSubmit(
      values.birth_date || "",
      hasInquiry === true
    ),
    // city is for user info (personal info) - use person_city from personal info
    city: values.person_city || values.city || "",
    // city_name is for guild info
    city_name: values.city_name || "",
    // province is stored as ID when selected, or as name from state field
    province: values.province || "",
    address: values.address || "",
    postalcode: values.postal_code || "",
    licenseNumber: values.license_number || "",
    licenseExpireDate: formatDateForSubmit(
      values.license_expire_date || "",
      hasInquiry === true
    ),
    licenseIssueDate: formatDateForSubmit(
      values.license_issue_date || "",
      hasInquiry === true
    ),
    licenseType: values.license_type || "",
    licenseStatus: values.license_status || "",
    isicname: values.area_activity || "",
    corporationName: values.corporation_name || "",
    nationalId: values.guild_national_id || "",
    unionName: values.union_name || "",
    phonenumber: values.phone_number || "",
    hasPartner: values.has_partner === true || values.has_partner === "بلی",
    isForeigner: values.is_foreigner === true || values.is_foreigner === "بلی",
    title: values.guild_name || "",
    role: getRoleFromUrl(),
    has_inquiry: hasInquiry !== null ? hasInquiry : false,
    ...(values.active !== null && { active: values.active }),
  };

  if (guild) {
    baseData.guilds_key = guild.key;
    if (values.mobile !== originalPhoneNumber) {
      baseData.mobile = values.mobile;
      baseData.mobilenumber = values.mobile;
    }
  }

  return baseData;
};

/**
 * Extracts form field values from database inquiry response
 * Data source: Inquiry national code which returns data from our database (dbRegister === true)
 */
const extractFormFieldsFromDatabaseInquiry = (
  responseDataFromDb,
  inquiryNationalCode
) => {
  const userFromDb = responseDataFromDb.user || {};
  const firstGuildFromDb =
    Array.isArray(responseDataFromDb.guilds) &&
    responseDataFromDb.guilds.length > 0
      ? responseDataFromDb.guilds[0]
      : {};
  const addressFromDb = firstGuildFromDb?.address || {};
  const provinceFromDb = addressFromDb.province || {};
  const cityFromDb = addressFromDb.city || {};

  return {
    // Personal Information Fields
    first_name: userFromDb.firstName || "",
    last_name: userFromDb.lastName || "",
    national_id: String(userFromDb.nationalId || inquiryNationalCode).trim(),
    national_code: userFromDb.nationalCode || "",
    birth_date: normalizeDatabaseDate(userFromDb.birthday || ""),
    father_name: userFromDb.fatherName || "",
    gender: userFromDb.gender || "",
    person_city: userFromDb.city || "",
    is_alive:
      userFromDb.isAlive === false
        ? "خیر"
        : userFromDb.isAlive === true
        ? "بلی"
        : "",
    mobile: userFromDb.mobile || "",

    // Guild Information Fields
    guild_name: firstGuildFromDb.guildsName || "",
    area_activity: firstGuildFromDb.areaActivity || "",
    state: provinceFromDb.name || "",
    province: provinceFromDb.key || "",
    city: cityFromDb.key || "",
    address: addressFromDb.address || "",
    license_expire_date: normalizeDatabaseDate(
      firstGuildFromDb.licenseExpireDate || ""
    ),
    license_status: firstGuildFromDb.licenseStatus || "",
    license_type: firstGuildFromDb.licenseType || "",
    license_number: firstGuildFromDb.licenseNumber || "",
    license_issue_date: normalizeDatabaseDate(
      responseDataFromDb.licenseIssueDate || ""
    ),
    union_name: firstGuildFromDb.unionName || "",
    postal_code: addressFromDb.postalCode || "",
    phone_number: firstGuildFromDb.phoneNumber || "",
    guild_national_id: firstGuildFromDb.nationalCode || "",
    corporation_name: firstGuildFromDb.companyName || "",

    // Status Fields
    is_foreigner:
      responseDataFromDb.isForeignNational === false
        ? false
        : responseDataFromDb.isForeignNational === true
        ? true
        : "",
    has_steward:
      responseDataFromDb.steward === false
        ? false
        : responseDataFromDb.steward === true
        ? true
        : "",
    has_partner:
      responseDataFromDb.hasPartner === false
        ? false
        : responseDataFromDb.hasPartner === true
        ? true
        : "",
    steward: firstGuildFromDb.isSteward || false,
    guild:
      typeof firstGuildFromDb.guild === "boolean"
        ? firstGuildFromDb.guild
        : false,

    // Additional Database Fields
    company_name: firstGuildFromDb.companyName || "",
    company_identifier: firstGuildFromDb.companyIdentifier || "",
    type_activity_name: firstGuildFromDb.typeActivity || "",
  };
};

/**
 * Extracts form field values from external API inquiry response
 * Data source: Inquiry national code which doesn't return data from our database (dbRegister === false)
 */
const extractFormFieldsFromExternalApi = (
  responseDataFromExternalApi,
  inquiryNationalCode
) => {
  const userFromExternalApi = responseDataFromExternalApi.user || {};
  const firstGuildFromExternalApi =
    Array.isArray(responseDataFromExternalApi.guilds) &&
    responseDataFromExternalApi.guilds.length > 0
      ? responseDataFromExternalApi.guilds[0]
      : {};
  const layerTwoFromExternalApi = firstGuildFromExternalApi.layerTwo || {};

  return {
    // Personal Information Fields
    first_name: userFromExternalApi.firstName || "",
    last_name: userFromExternalApi.lastName || "",
    national_id: String(
      layerTwoFromExternalApi.nationalcode ||
        userFromExternalApi.nationalCode ||
        inquiryNationalCode
    ).trim(),
    national_code: userFromExternalApi.identityNo || "",
    birth_date: normalizeExternalApiDate(userFromExternalApi.birthDate || ""),
    father_name: userFromExternalApi.fatherName || "",
    gender:
      userFromExternalApi.gender === true
        ? "True"
        : userFromExternalApi.gender === false
        ? "False"
        : "",
    person_city: userFromExternalApi.city || "",
    is_alive:
      userFromExternalApi.isLive === true
        ? "بلی"
        : userFromExternalApi.isLive === false
        ? "خیر"
        : "",
    mobile: layerTwoFromExternalApi.mobilenumber || "",

    // Guild Information Fields
    guild_name: firstGuildFromExternalApi.title || "",
    area_activity: firstGuildFromExternalApi.isicname || "",
    state: firstGuildFromExternalApi.state || "",
    province: "", // External API doesn't provide province ID
    city: firstGuildFromExternalApi.city || "",
    address: firstGuildFromExternalApi.address || "",
    license_expire_date: normalizeExternalApiDate(
      firstGuildFromExternalApi.licenseExpireDate || ""
    ),
    license_status: firstGuildFromExternalApi.licenseStatus || "",
    license_type: firstGuildFromExternalApi.licenseType || "",
    license_number: firstGuildFromExternalApi.licenseNumber || "",
    license_issue_date: normalizeExternalApiDate(
      layerTwoFromExternalApi.licenseIssueDate || ""
    ),
    union_name: layerTwoFromExternalApi.unionName || "",
    postal_code: layerTwoFromExternalApi.postalcode || "",
    phone_number: layerTwoFromExternalApi.phonenumber || "",
    guild_national_id: layerTwoFromExternalApi.nationalId || "",
    corporation_name: layerTwoFromExternalApi.corporationName || "",

    // Status Fields
    is_foreigner:
      layerTwoFromExternalApi.isForeigner === "خیر"
        ? false
        : layerTwoFromExternalApi.isForeigner === "بلی"
        ? true
        : "",
    has_steward:
      layerTwoFromExternalApi.hasSteward === "خیر"
        ? false
        : layerTwoFromExternalApi.hasSteward === "بلی"
        ? true
        : "",
    has_partner:
      layerTwoFromExternalApi.hasPartner === "خیر"
        ? false
        : layerTwoFromExternalApi.hasPartner === "بلی"
        ? true
        : "",
    steward: false, // External API doesn't provide steward status
    guild:
      typeof firstGuildFromExternalApi.guild === "boolean"
        ? firstGuildFromExternalApi.guild
        : false,
  };
};

/**
 * Maps response data to form fields based on data source
 *
 * Three data sources:
 * 1. Edit mode: Guild data passed as prop (handled by getInitialValues in formUtils.js)
 * 2. Database inquiry: Inquiry national code which returns data from our database (dbRegister === true)
 * 3. External API inquiry: Inquiry national code which doesn't return data from our database (dbRegister === false)
 */
export const mapResponseDataToFormFields = (
  responseData,
  inquiryNationalCode,
  formik
) => {
  const isFromExternalApi = responseData.dbRegister === false;

  // Route to appropriate extractor based on data source
  const formFieldValues = isFromExternalApi
    ? extractFormFieldsFromExternalApi(responseData, inquiryNationalCode)
    : extractFormFieldsFromDatabaseInquiry(responseData, inquiryNationalCode);

  formik.setValues({ ...formik.values, ...formFieldValues });
};
