<script setup lang="ts">
import { ref } from 'vue'
import { useConfigStore } from '../../stores/config'
import { useUiStore } from '../../stores/ui'
import { configApi } from '../../services/configApi'

const configStore = useConfigStore()
const ui = useUiStore()
const inferring = ref(false)

async function inferJoins() {
  inferring.value = true
  try {
    const { data } = await configApi.inferJoins()
    ui.showToast(`Found ${data.inferred} relationships, saved ${data.saved}`, 'success')
    await configStore.fetchJoins()
  } catch {
    ui.showToast('Auto-inference failed', 'error')
  } finally {
    inferring.value = false
  }
}

async function deleteJoin(id: string) {
  await configApi.deleteJoin(id)
  await configStore.fetchJoins()
  ui.showToast('Join removed', 'info')
}
</script>

<template>
  <div class="max-w-4xl">
    <div class="flex items-center justify-between mb-4">
      <h2 class="text-lg font-semibold">Join Relationships</h2>
      <button @click="inferJoins" :disabled="inferring" class="btn-primary text-sm">
        {{ inferring ? 'Detecting...' : 'Auto-Detect Joins' }}
      </button>
    </div>

    <div v-for="join in configStore.joins" :key="join.id" class="card mb-3 flex items-center justify-between">
      <div class="text-sm">
        <span class="font-mono text-primary-400">{{ join.left_table }}.{{ join.left_column }}</span>
        <span class="text-dark-500 mx-2">{{ join.join_type }} JOIN</span>
        <span class="font-mono text-primary-400">{{ join.right_table }}.{{ join.right_column }}</span>
        <span v-if="join.description" class="text-dark-500 text-xs ml-2">({{ join.description }})</span>
      </div>
      <button @click="deleteJoin(join.id)" class="text-dark-500 hover:text-red-400 text-xs">Remove</button>
    </div>

    <p v-if="!configStore.joins.length" class="text-dark-500 text-center py-8">
      No joins defined. Click "Auto-Detect" to discover relationships.
    </p>
  </div>
</template>
