import { resolve } from "@scalar/workspace-store/resolve";
import { isTypeObject } from "./is-type-object.js";
const reduceNamesToObject = (names, properties) => names.reduce((acc, name) => {
  const prop = properties?.[name];
  if (prop) {
    acc[name] = prop;
  }
  return acc;
}, {});
const sortPropertyNames = (schema, discriminator, {
  hideReadOnly = false,
  hideWriteOnly = false,
  orderSchemaPropertiesBy = "alpha",
  orderRequiredPropertiesFirst = true
} = {}) => {
  if (!isTypeObject(schema) || !schema.properties) {
    return [];
  }
  const propertyNames = Object.keys(schema.properties);
  const requiredPropertiesSet = new Set(schema.required || []);
  return propertyNames.sort((a, b) => {
    const aDiscriminator = a === discriminator?.propertyName;
    const bDiscriminator = b === discriminator?.propertyName;
    const aRequired = requiredPropertiesSet.has(a);
    const bRequired = requiredPropertiesSet.has(b);
    if (aDiscriminator && !bDiscriminator) {
      return -1;
    }
    if (!aDiscriminator && bDiscriminator) {
      return 1;
    }
    if (orderRequiredPropertiesFirst) {
      if (aRequired && !bRequired) {
        return -1;
      }
      if (!aRequired && bRequired) {
        return 1;
      }
    }
    if (orderSchemaPropertiesBy === "alpha") {
      return a.localeCompare(b);
    }
    return 0;
  }).filter((property) => {
    const resolved = schema.properties && resolve.schema(schema.properties[property]);
    if (hideReadOnly && resolved?.readOnly === true) {
      return false;
    }
    if (hideWriteOnly && resolved?.writeOnly === true) {
      return false;
    }
    return true;
  });
};
export {
  reduceNamesToObject,
  sortPropertyNames
};
