<script lang="ts">
	import QRScanner from './QRScanner.svelte';
	import TicketDisplay from './TicketDisplay.svelte';

	import type { TicketData } from '$lib/types';
	import { ScanState, defaultTicketData } from '$lib/types';

	let { data } = $props();
	let scanned_id = $state<string>("");
	let ticket_data = $state<TicketData>(defaultTicketData);
	let scan_state = $state<ScanState>(ScanState.scanning);

	$effect(() => {
		if (scanned_id === "") return;
		scan_state = ScanState.scanning;

		data.supabase
			.from('qrcodes')
			.select(`*, event ( id, name ), scanned_by ( id, display_name )`)
			.eq('id', scanned_id)
			.then( response => {
			if (response.data && response.data.length > 0) {
				ticket_data = response.data[0];
				scan_state = ScanState.scan_successful;
				data.supabase.rpc('scan_ticket', { _ticket_id: scanned_id}).then();
			} else {
				ticket_data = defaultTicketData;
				scan_state = ScanState.scan_failed;
			}
		})
	});
</script>

<QRScanner bind:message={scanned_id} />

<TicketDisplay {ticket_data} {scan_state}/>
