import CONSTANTS from "../../config/constants";
import propertyDB from "../../models/property.model";
import staffDB from "../../models/staff.model";
import propertiesTypes from "../../schemas/property.schema";

export const getStaffLinkedProperties = async (staffId: number, clientId: number, userType: number, isPartner: boolean) => {
    let iterableProperties = null;

    let linkedProperties = await staffDB.getLinkedProperties({
      staffId,
      clientId,
    });
    const allProperties = await propertyDB.getActivePropIdsByClientId({
      clientId,
      status: CONSTANTS.PROPERTY_STATUS.ACTIVE,
    });

    iterableProperties = allProperties || [];

    if (userType === CONSTANTS.USER_TYPE.STAFF && !isPartner) {
      const staffLinkedProps = await propertyDB.getPropsByStaffId({
        staffId: staffId,
      });

      iterableProperties = staffLinkedProps || [];
    }

    const mergedProps = [
      ...(iterableProperties || []),
      ...(linkedProperties || []),
    ];

    const uniqueProps = Array.from(
      new Map(mergedProps.map((prop: propertiesTypes) => [prop.id, prop])).values()
    );

    const combinedPropList = uniqueProps.map(
      (property: propertiesTypes) => {
        let isExists = false;
        if (linkedProperties) {
          isExists = linkedProperties.find(
            (prop: propertiesTypes) => prop.id === property.id
          );
        }
        return {
          id: property.id,
          name: property.name,
          isLinked: isExists ? 1 : 0,
        };
      }
    );
    return combinedPropList;
};

export default getStaffLinkedProperties;
