import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { requireAuthAndJson } from '$lib/server/task-helpers';
import { resolveReminderTime, upsertPreference } from '$lib/server/preferences-helpers';

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) => {
	const ctx = await requireAuthAndJson(event);
	if (ctx instanceof Response) return ctx;
	const { userId, payload } = ctx;

	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();

	const resolved = resolveReminderTime(db, userId, freqRaw, timeRaw);
	if ('error' in resolved) {
		return new Response(JSON.stringify({ error: resolved.error }), {
			status: 400,
			headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
		});
	}
	const { timeToSave } = resolved;

	upsertPreference(db, userId, freqRaw, timeToSave);

	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' }
	});
};
