import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { getAchievementsD1, getAchievementD1, createAchievementD1 } from '@/lib/d1';

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

    const achievements = await getAchievementsD1(session.user.id);

    return NextResponse.json(
      achievements.map((a) => ({
        badgeId: a.badgeId,
        unlockedAt: a.unlockedAt,
        substance: a.substance,
      }))
    );
  } catch (error) {
    console.error('Error fetching achievements:', 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 { badgeId?: string; substance?: string };
    const { badgeId, substance } = body;

    if (!badgeId || !substance) {
      return NextResponse.json({ error: 'Missing badgeId or substance' }, { status: 400 });
    }

    // Check if already exists
    const existing = await getAchievementD1(session.user.id, badgeId, substance);
    if (existing) {
      return NextResponse.json({
        badgeId: existing.badgeId,
        unlockedAt: existing.unlockedAt,
        substance: existing.substance,
        alreadyUnlocked: true,
      });
    }

    const achievement = await createAchievementD1(session.user.id, badgeId, substance);

    if (!achievement) {
      return NextResponse.json({ error: 'Failed to unlock achievement' }, { status: 500 });
    }

    return NextResponse.json({
      badgeId: achievement.badgeId,
      unlockedAt: achievement.unlockedAt,
      substance: achievement.substance,
      alreadyUnlocked: false,
    });
  } catch (error) {
    console.error('Error unlocking achievement:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
