import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { getPreferencesD1, upsertPreferencesD1 } from '@/lib/d1';

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

    const preferences = await getPreferencesD1(session.user.id);

    if (!preferences) {
      return NextResponse.json({
        substance: 'nicotine',
        trackingStartDate: null,
        hasCompletedSetup: false,
        dailyGoal: null,
        quitPlan: null,
        userName: null,
        userAge: null,
      });
    }

    return NextResponse.json({
      substance: preferences.substance,
      trackingStartDate: preferences.trackingStartDate,
      hasCompletedSetup: !!preferences.hasCompletedSetup,
      dailyGoal: preferences.dailyGoal,
      quitPlan: preferences.quitPlanJson ? JSON.parse(preferences.quitPlanJson) : null,
      userName: preferences.userName,
      userAge: preferences.userAge,
      religion: preferences.religion,
      lastNicotineUsageTime: preferences.lastNicotineUsageTime,
      lastWeedUsageTime: preferences.lastWeedUsageTime,
    });
  } catch (error) {
    console.error('Error fetching preferences:', 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 {
      substance?: string;
      trackingStartDate?: string;
      hasCompletedSetup?: boolean;
      dailyGoal?: number;
      quitPlan?: unknown;
      userName?: string;
      userAge?: number;
      religion?: string;
      lastNicotineUsageTime?: string;
      lastWeedUsageTime?: string;
    };

    const preferences = await upsertPreferencesD1(session.user.id, {
      substance: body.substance,
      trackingStartDate: body.trackingStartDate,
      hasCompletedSetup: body.hasCompletedSetup ? 1 : 0,
      dailyGoal: body.dailyGoal,
      quitPlanJson: body.quitPlan ? JSON.stringify(body.quitPlan) : undefined,
      userName: body.userName,
      userAge: body.userAge,
      religion: body.religion,
      lastNicotineUsageTime: body.lastNicotineUsageTime,
      lastWeedUsageTime: body.lastWeedUsageTime,
    });

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

    return NextResponse.json({
      substance: preferences.substance,
      trackingStartDate: preferences.trackingStartDate,
      hasCompletedSetup: !!preferences.hasCompletedSetup,
      dailyGoal: preferences.dailyGoal,
      quitPlan: preferences.quitPlanJson ? JSON.parse(preferences.quitPlanJson) : null,
      userName: preferences.userName,
      userAge: preferences.userAge,
      religion: preferences.religion,
      lastNicotineUsageTime: preferences.lastNicotineUsageTime,
      lastWeedUsageTime: preferences.lastWeedUsageTime,
    });
  } catch (error) {
    console.error('Error saving preferences:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
