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: Record<string, string[]> = {
    amazing: [
        "Incredible! Use this energy to stay smoke-free!",
        "You're on fire! Keep living your best life.",
        "So happy for you! This is what freedom feels like.",
        "Outstanding! Bottle this feeling for later.",
        "You're unstoppable today! Keep it up.",
        "Radiating positivity! Your journey is inspiring.",
        "Top of the world! Enjoy every moment of this success.",
        "Absolutely brilliant! You're glowing with health.",
        "Peak performance! This is the real you shining through.",
        "Marvelous! Your commitment is paying off in spades.",
        "What a feeling! You're crushing your goals.",
        "Sky high! nothing can bring you down today."
    ],
    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.",
        "Great vibes! A healthy life looks good on you.",
        "Feeling good is just the beginning. It gets better.",
        "Solid progress! You're building a beautiful future.",
        "Nice! Enjoy this clarity and energy.",
        "You're doing it! Every good day is a victory.",
        "Beautiful! Your body thanks you for your choices.",
        "Keep smiling! You're on the right path."
    ],
    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.",
        "Calm waters run deep. You're staying strong.",
        "Consistency is your superpower. Keep showing up.",
        "A quiet day is a good day. Stay committed.",
        "Just keep swimming. You're doing just fine.",
        "Neutral ground is safe ground. protecting your progress.",
        "Peaceful and present. That's a win in itself.",
        "Center yourself. You are in control."
    ],
    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.",
        "Storms run out of rain. This too shall pass.",
        "Your journey is worth it, even on hard days.",
        "Don't lose hope. You've come so far already.",
        "Courage is keeping on when it's hard. You valid.",
        "Treat yourself with extra care today. You deserve it.",
        "One breath at a time. You can get through this.",
        "Sending you strength. You are not alone."
    ],
    terrible: [
        "It's okay to not be okay. Just breathe.",
        "This moment will pass. You are stronger than this usage.",
        "Reaching out for support is a sign of strength.",
        "Be gentle with yourself. You're fighting a hard battle.",
        "Don't give up. The sun will rise again.",
        "You are resilient. You can weather this storm.",
        "Hold on. Better days are coming.",
        "Your worth is not defined by this moment.",
        "Scream if you need to, but don't give up.",
        "It's darkest before dawn. Keep fighting.",
        "You are loved and you are capable. Stay with us.",
        "This pain is temporary, your freedom is forever."
    ]
};

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: 'amazing' | 'good' | 'neutral' | 'bad' | 'terrible'; score: number; comment?: string; date?: string };
        const { mood, score, comment, date } = body;

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

        if (comment && (typeof comment !== 'string' || comment.length > 500)) {
            return NextResponse.json({ error: 'Comment too long' }, { status: 400 });
        }

        if (date && !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
            return NextResponse.json({ error: 'Invalid date format' }, { status: 400 });
        }

        // Validate score is between 0 and 100
        const finalScore = Math.max(0, Math.min(100, score ?? 50));

        const entryDate = date || getTodayString();
        const entry = await saveMoodEntryD1(session.user.id, mood, finalScore, entryDate, comment);

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

        // Pick a random affirmation
        let affirmation = "You're doing great! Keep it up.";
        try {
            const moodAffirmations = AFFIRMATIONS[mood] || AFFIRMATIONS['neutral'];
            if (moodAffirmations && moodAffirmations.length > 0) {
                affirmation = moodAffirmations[Math.floor(Math.random() * moodAffirmations.length)];
            }
        } catch (affError) {
            console.error('Error selecting affirmation:', affError);
            // Fallback is already set
        }

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