<script setup lang="ts">

import {RuleClauseResponse} from "@/generated/mammon";
import {computed, watch} from "vue";
import {systemLedgerRef} from "@/ledger";
import {ratesTypes} from "@/rules/rules.ts";
import LedgerRefSelect from "./LedgerRefSelect.vue";

interface Props {
  ledgerRefs: string[];
}

const props = defineProps<Props>()

const rule = defineModel<RuleClauseResponse>({ default: {
    rate: ratesTypes.None,
    fromLedgerRef: systemLedgerRef,
    toLedgerRef: systemLedgerRef,
  }});

const ledgerRefsWithSystem = computed<string[]>(() => [systemLedgerRef, ...props.ledgerRefs])

watch(ledgerRefsWithSystem, (newVal, oldVal) => {
  if (newVal.length !== oldVal.length) {
    return;
  }

  if (rule.value.fromLedgerRef && rule.value.fromLedgerRef !== systemLedgerRef) {
    rule.value.fromLedgerRef = newVal[oldVal.findIndex(v => v === rule.value.fromLedgerRef)]
  }
  if (rule.value.toLedgerRef && rule.value.toLedgerRef !== systemLedgerRef) {
    rule.value.toLedgerRef = newVal[oldVal.findIndex(v => v === rule.value.toLedgerRef)]
  }
})
</script>

<template>
  From:
  <LedgerRefSelect class="me-2 grow" v-model="rule.fromLedgerRef" :ledger-refs="ledgerRefsWithSystem"/>
  To:
  <LedgerRefSelect class="me-2 grow" v-model="rule.toLedgerRef" :ledger-refs="ledgerRefsWithSystem"/>
  At:
  <select class="me-2 grow" v-model="rule.rate">
    <option v-for="rateType in ratesTypes" :key="rateType.key" :value="rateType.key">{{ rateType.name }}</option>
  </select>
</template>