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

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

    const config = await getSavingsConfigD1(session.user.id);

    if (!config) {
      return NextResponse.json(null);
    }

    return NextResponse.json({
      costPerUnit: config.costPerUnit,
      unitsPerDay: config.unitsPerDay,
      savingsGoal: config.savingsGoal,
      goalName: config.goalName,
      currency: config.currency,
      substance: config.substance,
    });
  } catch (error) {
    console.error('Error fetching savings config:', 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 {
      costPerUnit?: number;
      unitsPerDay?: number;
      savingsGoal?: number;
      goalName?: string;
      currency?: string;
      substance?: string;
    };
    const { costPerUnit, unitsPerDay, savingsGoal, goalName, currency, substance } = body;

    if (costPerUnit === undefined || unitsPerDay === undefined || !substance) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const config = await upsertSavingsConfigD1(
      session.user.id,
      costPerUnit,
      unitsPerDay,
      substance,
      savingsGoal,
      goalName,
      currency
    );

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

    return NextResponse.json({
      costPerUnit: config.costPerUnit,
      unitsPerDay: config.unitsPerDay,
      savingsGoal: config.savingsGoal,
      goalName: config.goalName,
      currency: config.currency,
      substance: config.substance,
    });
  } catch (error) {
    console.error('Error saving savings config:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
