import { watch, type ComputedRef } from "vue";
import { toSlug } from "@/lib/slug";

type AutoGenerateField = {
  name: string;
  generateFrom: string | null;
};

export function useAutoGenerateFields(
  form: Record<string, unknown>,
  allFields: ComputedRef<AutoGenerateField[]>,
  initialData: Record<string, unknown>,
): void {
  const manuallyOverridden = new Set<string>(
    allFields.value
      .filter((f) => f.generateFrom && initialData[f.name])
      .map((f) => f.name),
  );

  allFields.value.forEach((field) => {
    if (!field.generateFrom) return;

    const sourceField = field.generateFrom;
    let programmatic = false;

    watch(
      () => form[sourceField],
      (val) => {
        if (manuallyOverridden.has(field.name)) return;
        programmatic = true;
        form[field.name] = toSlug(String(val ?? ""));
        programmatic = false;
      },
    );

    watch(
      () => form[field.name],
      () => {
        if (!programmatic) {
          manuallyOverridden.add(field.name);
        }
      },
      { flush: "sync" },
    );
  });
}
