<template>
  <DefaultInput
    ref="inputRef"
    v-model="formattedValue"
    v-bind="$attrs"
    :error-message="errorMessage"
    :input-class="inputClass"
    :label="label"
    :rules="finalRules"
  />
</template>

<script setup>
import { computed, watch } from "vue";
import { useCurrencyInput } from "vue-currency-input";
import { useInputRules } from "src/composables/useInputRules";

import DefaultInput from "./DefaultInput.vue";

const { inputRules } = useInputRules();

const model = defineModel({ type: Number });

const { options, label, rules, errorMessage } = defineProps({
  errorMessage: {
    type: String,
    default: undefined,
  },
  inputClass: {
    type: String,
    default: "",
  },
  label: {
    type: String,
    default: "Valor",
  },
  options: {
    type: Object,
    default: () => ({
      accountingSign: false,
      autoDecimalDigits: true,
      currency: "BRL",
      currencyDisplay: "symbol",
      hideCurrencySymbolOnFocus: false,
      hideGroupingSeparatorOnFocus: false,
      hideNegligibleDecimalDigitsOnFocus: false,
      locale: "pt-BR",
      useGrouping: true,
    }),
  },
  rules: {
    type: Array,
    default: () => [],
  },
});

const { inputRef, formattedValue, numberValue, setValue } =
  useCurrencyInput(options);

const minRule = inputRules.minValue(0);

const wrapRule = (rule) => {
  const wrapped = (value) => rule(numberValue.value, value);
  if (rule?.$id) wrapped.$id = rule.$id;
  return wrapped;
};

const finalRules = computed(() => [
  ...rules.map(wrapRule),
  () => minRule(numberValue.value),
]);

watch(
  () => model.value,
  (newValue) => {
    setValue(newValue);
  },
);

watch(
  () => numberValue.value,
  (newValue) => {
    model.value = newValue;
  },
);
</script>
