import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { getMoodEntriesD1, saveMoodEntryD1 } from '@/lib/d1';
import { getTodayString } from '@/lib/date-utils';

const AFFIRMATIONS = {
    good: [
        "That's wonderful! Keep riding this positive wave.",
        "Your strength is inspiring. Keep going!",
        "Happiness is a great companion on this journey.",
        "So glad you're feeling good! You've got this.",
        "Keep that momentum! You're doing amazing."
    ],
    neutral: [
        "Steady as she goes. Every day is progress.",
        "It's okay to just 'be' sometimes. Stay the course.",
        "Focus on your 'why' today. You're doing great.",
        "One step at a time. You're still moving forward.",
        "Balance is key. Keep your goals in sight."
    ],
    bad: [
        "I'm sorry things are tough. This feeling is temporary.",
        "Be kind to yourself today. You're still stronger than you think.",
        "Tough times don't last, but tough people do. Hang in there.",
        "Take a deep breath. Tomorrow is a fresh start.",
        "It's okay to struggle. What matters is that you keep trying."
    ]
};

export async function GET() {
    try {
        const session = await getSession();
        if (!session?.user) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const entries = await getMoodEntriesD1(session.user.id);
        return NextResponse.json(entries);
    } catch (error) {
        console.error('Error fetching mood entries:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

export async function POST(request: NextRequest) {
    try {
        const session = await getSession();
        if (!session?.user) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const body = await request.json() as { mood: 'good' | 'neutral' | 'bad'; comment?: string };
        const { mood, comment } = body;

        if (!mood || !['good', 'neutral', 'bad'].includes(mood)) {
            return NextResponse.json({ error: 'Invalid mood' }, { status: 400 });
        }

        const today = getTodayString();
        const entry = await saveMoodEntryD1(session.user.id, mood, today, comment);

        if (!entry) {
            return NextResponse.json({ error: 'Failed to save mood entry' }, { status: 500 });
        }

        // Pick a random affirmation
        const moodAffirmations = AFFIRMATIONS[mood];
        const affirmation = moodAffirmations[Math.floor(Math.random() * moodAffirmations.length)];

        return NextResponse.json({ entry, affirmation });
    } catch (error) {
        console.error('Error saving mood entry:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
