<template>
  <div class="flex flex-col gap-2 w-full">
    <TableSelect v-model="table" :disableTableSelect="disableTableSelect" />
    <ColumnSelect v-if="table != ''" v-model="columnSelect" :table="table" />
    <Where v-if="table != ''" v-model="where" :table="table" />
    <Join v-if="table != ''" v-model="modelValue.join" :table="table" :alreadyJoined="alreadyJoined" />
    <Order v-if="table != '' && enableOrder" v-model="order" :table="table" :columns="nestedTablesByDepth" />
  </div>
</template>

<script setup lang="ts">
import { defineComponent, type PropType } from "vue";
import { type ConditionStructure, type DynamicQueryStructure, type OrderByStructure } from "@/types/dynamicQueries";
import ColumnSelect from "./ColumnSelect.vue";
import Where from "./Where.vue";
import Order from "./Order.vue";
import Join from "./Join.vue";
import TableSelect from "./TableSelect.vue";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    modelValue: {
      type: Object as PropType<DynamicQueryStructure>,
      required: true,
    },
    disableTableSelect: {
      type: Boolean,
      default: false,
    },
    enableOrder: {
      type: Boolean,
      default: false,
    },
  },
  emits: ["update:model-value"],
  computed: {
    alreadyJoined() {
      return this.modelValue.join?.map((j) => j.table);
    },
    nestedTablesByDepth() {
      const tables: Array<{ table: string; id: string; depth: number; path: string[]; columns: "*" | string[] }> = [];

      function recurse(item: DynamicQueryStructure, path: string[]) {
        tables.push({ table: item.table, id: item.id, depth: path.length, path, columns: item.select });
        if (item.join) {
          item.join.forEach((child) => {
            recurse(child, [...path, item.table]);
          });
        }
      }

      recurse(this.modelValue, []);

      return tables;
    },
    table: {
      get() {
        return this.modelValue.table || "";
      },
      set(val: string) {
        this.$emit("update:model-value", { ...this.modelValue, table: val });
      },
    },
    columnSelect: {
      get() {
        return this.modelValue.select;
      },
      set(val: "*" | Array<string>) {
        this.$emit("update:model-value", { ...this.modelValue, select: val });
      },
    },
    where: {
      get() {
        return this.modelValue.where;
      },
      set(val: Array<ConditionStructure>) {
        this.$emit("update:model-value", { ...this.modelValue, where: val });
      },
    },
    order: {
      get() {
        return this.modelValue.orderBy;
      },
      set(val: Array<OrderByStructure>) {
        this.$emit("update:model-value", { ...this.modelValue, orderBy: val });
      },
    },
    join: {
      get() {
        return this.modelValue.join;
      },
      set(val: Array<DynamicQueryStructure & { foreignColumn: string }>) {
        this.$emit("update:model-value", { ...this.modelValue, join: val });
      },
    },
  },
});
</script>
