import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { normalizeTime } from '$lib/server/datetime';

export const GET: RequestHandler = async (event) => {
	// Requiere sesión
	const userId = event.locals.userId ?? null;
	if (!userId) {
		return new Response('Unauthorized', { status: 401 });
	}

	const db = await getDb();
	const row = db
		.prepare(
			`SELECT reminder_freq AS freq, reminder_time AS time
       FROM user_preferences
       WHERE user_id = ?
       LIMIT 1`
		)
		.get(userId) as any;

	const body =
		row && row.freq
			? { freq: String(row.freq), time: row.time ? String(row.time) : null }
			: { freq: 'off', time: '08:30' };

	return new Response(JSON.stringify(body), {
		status: 200,
		headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
	});
};

export const POST: RequestHandler = async (event) => {
	// Requiere sesión
	const userId = event.locals.userId ?? null;
	if (!userId) {
		return new Response('Unauthorized', { status: 401 });
	}

	let payload: unknown = null;
	try {
		payload = await event.request.json();
	} catch {
		return new Response('Bad Request', { status: 400 });
	}
	const body = payload && typeof payload === 'object' ? (payload as { freq?: unknown; time?: unknown }) : null;

	const freqRaw = String(body?.freq ?? '').trim().toLowerCase();
	const timeRaw = body?.time == null ? null : String(body.time).trim();

	const allowed = new Set(['off', 'daily', 'weekly', 'weekdays']);
	if (!allowed.has(freqRaw)) {
		return new Response(JSON.stringify({ error: 'freq inválida' }), {
			status: 400,
			headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
		});
	}


	const db = await getDb();

	let timeToSave: string | null = null;

	if (freqRaw === 'off') {
		// Hora opcional: si viene, validar/normalizar; si no, conservar la actual o usar '08:30'
		if (timeRaw && timeRaw.length > 0) {
			const norm = normalizeTime(timeRaw);
			if (!norm) {
				return new Response(JSON.stringify({ error: 'hora inválida' }), {
					status: 400,
					headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
				});
			}
			timeToSave = norm;
		} else {
			const row = db
				.prepare(
					`SELECT reminder_time AS time
           FROM user_preferences
           WHERE user_id = ?
           LIMIT 1`
				)
				.get(userId) as any;
			timeToSave = row?.time ? String(row.time) : '08:30';
		}
	} else {
		// daily/weekly/weekdays: si no se especifica hora, usar '08:30'
		if (!timeRaw || timeRaw.length === 0) {
			timeToSave = '08:30';
		} else {
			const norm = normalizeTime(timeRaw);
			if (!norm) {
				return new Response(JSON.stringify({ error: 'hora inválida' }), {
					status: 400,
					headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
				});
			}
			timeToSave = norm;
		}
	}

	// Upsert preferencia (mantener last_reminded_on intacto)
	db.prepare(
		`INSERT INTO user_preferences (user_id, reminder_freq, reminder_time, last_reminded_on, updated_at)
     VALUES (?, ?, ?, (SELECT last_reminded_on FROM user_preferences WHERE user_id = ?), strftime('%Y-%m-%d %H:%M:%f','now'))
     ON CONFLICT(user_id) DO UPDATE SET
       reminder_freq = excluded.reminder_freq,
       reminder_time = excluded.reminder_time,
       updated_at = excluded.updated_at`
	).run(userId, freqRaw, timeToSave, userId);

	const responseBody = { freq: freqRaw, time: timeToSave };

	return new Response(JSON.stringify(responseBody), {
		status: 200,
		headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
	});
};
