<script lang="ts">
import { m } from '$lib/paraglide/messages.js';

let backfillResult: number | null = $state(null);
let backfillLoading = $state(false);
let backfillHashesResult: number | null = $state(null);
let backfillHashesLoading = $state(false);

async function backfillVersions() {
	backfillLoading = true;
	backfillResult = null;
	try {
		const res = await fetch('/api/admin/backfill-versions', { method: 'POST' });
		if (res.ok) {
			const data = await res.json();
			backfillResult = data.count;
		}
	} finally {
		backfillLoading = false;
	}
}

async function backfillFileHashes() {
	backfillHashesLoading = true;
	backfillHashesResult = null;
	try {
		const res = await fetch('/api/admin/backfill-file-hashes', { method: 'POST' });
		if (res.ok) {
			const data = await res.json();
			backfillHashesResult = data.count;
		}
	} finally {
		backfillHashesLoading = false;
	}
}
</script>

<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
	<h2 class="mb-1 text-lg font-bold text-ink-2">{m.admin_system_backfill_heading()}</h2>
	<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_description()}</p>
	<button
		onclick={backfillVersions}
		disabled={backfillLoading}
		class="rounded bg-primary px-6 py-2 text-sm font-bold text-primary-fg uppercase transition hover:bg-accent hover:text-ink disabled:cursor-not-allowed disabled:opacity-50"
	>
		{backfillLoading ? '…' : m.admin_system_backfill_btn()}
	</button>
	{#if backfillResult !== null}
		<p class="mt-4 text-sm font-medium text-ink">
			{m.admin_system_backfill_success({ count: backfillResult })}
		</p>
	{/if}
</div>

<div class="mt-4 rounded-sm border border-line bg-surface p-6 shadow-sm">
	<h2 class="mb-1 text-lg font-bold text-ink-2">
		{m.admin_system_backfill_hashes_heading()}
	</h2>
	<p class="mb-4 text-sm text-ink-2">{m.admin_system_backfill_hashes_description()}</p>
	<button
		onclick={backfillFileHashes}
		disabled={backfillHashesLoading}
		class="rounded bg-primary px-6 py-2 text-sm font-bold text-primary-fg uppercase transition hover:bg-accent hover:text-ink disabled:cursor-not-allowed disabled:opacity-50"
	>
		{backfillHashesLoading ? '…' : m.admin_system_backfill_hashes_btn()}
	</button>
	{#if backfillHashesResult !== null}
		<p class="mt-4 text-sm font-medium text-ink">
			{m.admin_system_backfill_hashes_success({ count: backfillHashesResult })}
		</p>
	{/if}
</div>
