import type { RequestHandler } from './$types';
import { redirect } from '@sveltejs/kit';
import { getDb } from '$lib/server/db';
import { sha256Hex } from '$lib/server/crypto';
import { isProd } from '$lib/server/env';

export const POST: RequestHandler = async (event) => {
	const sid = event.cookies.get('sid');
	if (sid) {
		try {
			const db = await getDb();
			const hash = await sha256Hex(sid);
			// Intentar borrar; si falla, expirar
			try {
				db.prepare(`DELETE FROM web_sessions WHERE session_hash = ?`).run(hash);
			} catch {
				db.prepare(
					`UPDATE web_sessions
           SET expires_at = strftime('%Y-%m-%d %H:%M:%f','now')
           WHERE session_hash = ?`
				).run(hash);
			}
		} catch {
			// Ignorar errores de DB en logout
		}
	}
	// Limpiar cookie (asegurar mismos atributos que al crearla)
	event.cookies.delete('sid', { path: '/', httpOnly: true, sameSite: 'lax', secure: isProd() });

	// Redirigir a home para que el navegador navegue sin depender de JS
	throw redirect(303, '/');
};
