<template>
	<private-view title="Meili Sync">
		<template #title-outer:prepend>
			<v-icon name="feature_search" />
		</template>

		<template #navigation>
			<v-list nav :model-value="selected" dense>
				<v-list-item to="/meilisearch" exact>
					索引配置
				</v-list-item>
				<v-list-item to="/meilisearch/config">
					MeiliSearch 配置
				</v-list-item>
			</v-list>
		</template>

		<template #actions>
			<v-button xSmall color="primary" @click="handleReindexAll">
				一键重建
			</v-button>
		</template>

		<section>
			<v-notice type="info">请选择希望被 MeiliSearch 索引的集合。</v-notice>
			<v-table :headers="headers" :items="configs" :items-per-page="10" class="mt-4">
				<template #item.enabled="{ item }">
					<v-checkbox v-model="item.enabled" :label="item.enabled ? '已启用' : '未启用'" />
				</template>"

				<template #item.actions="{ item }">
					<v-button xSmall @click="handleReindex(item)">刷新索引</v-button>
				</template>
			</v-table>
		</section>

	</private-view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useApi } from '@directus/extensions-sdk';

const api = useApi();
const configs = ref([]);
const headers = [
	{ text: '集合名称', value: 'collection_name' },
	{ text: '索引名称', value: 'index_name' },
	{ text: '启用索引', value: 'enabled' },
	{ text: '操作', value: 'actions', sortable: false },
];

const fetchConfigs = async () => {
	const resp = await api.get('/items/meili_index_configs', { params: { limit: -1 } });
	configs.value = resp.data.data;
}

const handleReindexAll = async () => {
	try {
		await api.post('/meilisearch/reindex');
		console.log('Reindexing all started successfully');
	} catch (error) {
		console.error('Reindexing all failed:', error);
	}
}

const handleReindex = async (item: any) => {
	if (!item.enabled) return;
	const configId = item.id;
	try {
		await api.post(`/meilisearch/reindex/${configId}`);
		console.log('Reindexing started successfully');
	} catch (error) {
		console.error('Reindexing failed:', error);
	}

};

const selected = ref(null);

onMounted(() => {
	fetchConfigs();
})

</script>

<style scoped>
section {
	padding: 0 var(--content-padding);
}
</style>