import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getVerseForDate } from '$lib/server/daily-verse';

export const POST: RequestHandler = async ({ request }) => {
	const cronSecret = Bun.env.CRON_SECRET;
	const discordWebhook = Bun.env.DISCORD_DAILY_WEBHOOK;

	const authHeader = request.headers.get('Authorization');
	if (!authHeader || !cronSecret || authHeader !== `Bearer ${cronSecret}`) {
		return json({ error: 'Unauthorized' }, { status: 401 });
	}

	const dateStr = new Date().toLocaleDateString('en-CA', { timeZone: 'America/New_York' });

	const verse = await getVerseForDate(dateStr);

	const fullDate = new Date(dateStr + 'T00:00:00Z').toLocaleDateString('en-US', {
		year: 'numeric',
		month: 'long',
		day: 'numeric',
		timeZone: 'UTC',
	});

	const message = `*${fullDate}*\n**"${verse.verseText}"**`;

	if (!discordWebhook) {
		return json({ error: 'Discord webhook not configured' }, { status: 500 });
	}

	const discordResponse = await fetch(discordWebhook, {
		method: 'POST',
		headers: { 'Content-Type': 'application/json' },
		body: JSON.stringify({ content: message }),
	});

	if (!discordResponse.ok) {
		return json({ error: 'Failed to post to Discord' }, { status: 500 });
	}

	return json({ ok: true });
};
