<template>
  <div class="flex flex-row gap-2 w-full">
    <div class="flex flex-row gap-2 w-full">
      <div class="flex flex-col gap-2 w-full">
        <select v-model="foreignColumn" class="w-full">
          <option value="" disabled>Relation auswählen</option>
          <option v-for="relation in activeTable?.relations" :value="relation.column">
            {{ relation.column }} -> {{ joinTableName(relation.referencedTableName) }}
          </option>
        </select>
        <Table v-model="value" disable-table-select />
      </div>
      <div class="h-fit p-1 border border-gray-400 hover:bg-gray-200 rounded-md" @click="$emit('remove')">
        <TrashIcon class="text-gray-500 h-6 w-6 cursor-pointer" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import { mapActions, mapState } from "pinia";
import type { DynamicQueryStructure } from "../../types/dynamicQueries";
import { useQueryBuilderStore } from "../../stores/admin/queryBuilder";
import Table from "./Table.vue";
import { TrashIcon } from "@heroicons/vue/24/outline";
import { joinTableName } from "@/helpers/queryFormatter";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    table: {
      type: String,
      default: "",
    },
    modelValue: {
      type: Object as PropType<
        DynamicQueryStructure & {
          foreignColumn: string;
        }
      >,
      default: {
        select: "*",
        table: "",
        where: [],
        join: [],
        orderBy: [],
        foreignColumn: "",
      },
    },
  },
  emits: ["update:model-value", "remove"],
  data() {
    return {};
  },
  computed: {
    ...mapState(useQueryBuilderStore, ["tableMetas"]),
    activeTable() {
      return this.tableMetas.find((tm) => tm.tableName == this.table);
    },
    value: {
      get() {
        return this.modelValue;
      },
      set(
        val: DynamicQueryStructure & {
          foreignColumn: string;
        }
      ) {
        this.$emit("update:model-value", val);
      },
    },
    foreignColumn: {
      get() {
        return this.modelValue.foreignColumn;
      },
      set(val: string) {
        let relTable = this.activeTable?.relations.find((r) => r.column == val);
        this.$emit("update:model-value", {
          ...this.modelValue,
          foreignColumn: val,
          table: joinTableName(relTable?.referencedTableName ?? ""),
        });
      },
    },
  },
});
</script>
