import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getPublicWarungs } from '$lib/server/warung';
import type { KategoriWarung } from '$lib/types/warung';

const VALID_KATEGORI: KategoriWarung[] = [
	'jajanan',
	'makanan',
	'minuman',
	'sembako',
	'kelontong',
	'campuran'
];

export const GET: RequestHandler = async ({ url }) => {
	const q = url.searchParams.get('q') ?? undefined;
	const kota = url.searchParams.get('kota') ?? undefined;
	const kategoriParam = url.searchParams.get('kategori') ?? undefined;
	const kategori = VALID_KATEGORI.includes(kategoriParam as KategoriWarung)
		? (kategoriParam as KategoriWarung)
		: undefined;

	try {
		const warungs = await getPublicWarungs({ q, kota, kategori });

		return json({
			success: true,
			total: warungs.length,
			warungs
		});
	} catch {
		return json({ success: false, message: 'Gagal mengambil data warung.' }, { status: 500 });
	}
};
