<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { apiDelete, apiGet, apiPost, apiPut } from "../api";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";
import type { ApiConnector } from "../types";

const connectors = ref<ApiConnector[]>([]);
const selectedId = ref<string | null>(null);
const form = reactive({ code: "", name: "", connector_type: "generic_price_api", config: "{\n  \"base_url\": \"https://example.invalid\",\n  \"api_key\": \"dev\"\n}", is_active: true, sync_interval_minutes: 1440 as number | null });
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");
async function load() { const result = await apiGet<ApiConnector[]>("/api/v1/api-connectors"); if (result.ok) connectors.value = result.data; else { status.value = result.message; kind.value = "error"; } }
function createNew() { selectedId.value = null; Object.assign(form, { code: "", name: "", connector_type: "generic_price_api", config: "{\n  \"base_url\": \"https://example.invalid\",\n  \"api_key\": \"dev\"\n}", is_active: true, sync_interval_minutes: 1440 }); }
function select(connector: ApiConnector) { selectedId.value = connector.id; Object.assign(form, { code: connector.code, name: connector.name, connector_type: connector.connector_type, config: JSON.stringify(connector.config, null, 2), is_active: connector.is_active, sync_interval_minutes: connector.sync_interval_minutes ?? null }); }
function payload() { return { ...form, config: JSON.parse(form.config || "{}") }; }
async function save() {
  try {
    const result = selectedId.value ? await apiPut<ApiConnector>(`/api/v1/api-connectors/${selectedId.value}`, payload()) : await apiPost<ApiConnector>("/api/v1/api-connectors", payload());
    status.value = result.ok ? "Connector gespeichert." : result.message; kind.value = result.ok ? "success" : "error"; if (result.ok) { selectedId.value = result.data.id; await load(); }
  } catch { status.value = "Konfiguration ist kein gültiges JSON."; kind.value = "error"; }
}
async function sync() { if (!selectedId.value) return; const result = await apiPost(`/api/v1/api-connectors/${selectedId.value}/sync`, {}); status.value = result.ok ? "Abgleich ausgeführt." : result.message; kind.value = result.ok ? "success" : "error"; if (result.ok) await load(); }
async function deactivate() { if (!selectedId.value) return; const result = await apiDelete(`/api/v1/api-connectors/${selectedId.value}`); status.value = result.ok ? "Connector deaktiviert." : result.message; kind.value = result.ok ? "success" : "error"; if (result.ok) await load(); }
onMounted(load);
</script>
<template>
  <PageHeader title="Preis-APIs" description="Externe Preisquellen konfigurieren und manuell abgleichen." />
  <div class="workspace-split"><section class="panel list-panel"><div class="section-title"><h2>Connectoren</h2><button type="button" @click="createNew">Neu</button></div><button v-for="connector in connectors" :key="connector.id" type="button" class="list-row" :class="{ selected: selectedId === connector.id }" @click="select(connector)"><strong>{{ connector.code }}</strong><span>{{ connector.name }}</span><small>{{ connector.last_sync_at ?? "kein Abgleich" }}</small></button></section>
    <section class="panel detail-panel"><form @submit.prevent="save"><div class="form-grid"><label class="field"><span>Code</span><input v-model="form.code" required /></label><label class="field"><span>Name</span><input v-model="form.name" required /></label><label class="field"><span>Typ</span><input v-model="form.connector_type" required /></label><label class="field"><span>Intervall Minuten</span><input v-model="form.sync_interval_minutes" type="number" min="1" /></label><label class="check-row"><input v-model="form.is_active" type="checkbox" /><span>Aktiv</span></label><label class="field full-width"><span>Konfiguration JSON</span><textarea v-model="form.config" rows="8" /></label></div><div class="form-actions"><button type="submit">Speichern</button><button v-if="selectedId" type="button" class="secondary" @click="sync">Abgleichen</button><button v-if="selectedId" type="button" class="secondary" @click="deactivate">Deaktivieren</button></div><FormStatus :message="status" :kind="kind" /></form></section></div>
</template>
