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,
      });
    }

    // Parse JSON to construct quitState
    const rawJson = preferences.quitPlanJson ? JSON.parse(preferences.quitPlanJson) : null;
    const isNewFormat = rawJson && 'nicotine' in rawJson;
    const quitState = isNewFormat ? rawJson : {
      nicotine: preferences.substance === 'nicotine' ? { plan: rawJson, startDate: preferences.trackingStartDate } : { plan: null, startDate: null },
      weed: preferences.substance === 'weed' ? { plan: rawJson, startDate: preferences.trackingStartDate } : { plan: null, startDate: null }
    };

    return NextResponse.json({
      substance: preferences.substance,
      trackingStartDate: preferences.trackingStartDate,
      hasCompletedSetup: !!preferences.hasCompletedSetup,
      dailyGoal: preferences.dailyGoal,
      quitPlan: null,
      quitState,
      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;
      quitState?: unknown;
      userName?: string;
      userAge?: number;
      religion?: string;
      lastNicotineUsageTime?: string;
      lastWeedUsageTime?: string;
    };

    // Validation & Normalization
    if (body.substance && !['nicotine', 'weed'].includes(body.substance)) {
      return NextResponse.json({ error: 'Invalid substance' }, { status: 400 });
    }
    if (body.trackingStartDate && !/^\d{4}-\d{2}-\d{2}$/.test(body.trackingStartDate)) {
      return NextResponse.json({ error: 'Invalid trackingStartDate format' }, { status: 400 });
    }

    // Loose type checking for numbers (allow strings that parse to numbers)
    const dailyGoal = Number(body.dailyGoal);
    if (body.dailyGoal !== undefined && body.dailyGoal !== null && (isNaN(dailyGoal) || dailyGoal < 0)) {
      return NextResponse.json({ error: 'Invalid dailyGoal' }, { status: 400 });
    }

    const userAge = Number(body.userAge);
    if (body.userAge !== undefined && body.userAge !== null && (isNaN(userAge) || userAge < 0 || userAge > 120)) {
      return NextResponse.json({ error: 'Invalid userAge' }, { status: 400 });
    }

    if (body.religion && !['christian', 'secular'].includes(body.religion)) {
      return NextResponse.json({ error: 'Invalid religion' }, { status: 400 });
    }

    // If quitState is provided in body, save it to quitPlanJson
    const quitPlanJson = body.quitState
      ? JSON.stringify(body.quitState)
      : (body.quitPlan ? JSON.stringify(body.quitPlan) : undefined);

    const preferences = await upsertPreferencesD1(session.user.id, {
      substance: body.substance,
      trackingStartDate: body.trackingStartDate,
      hasCompletedSetup: body.hasCompletedSetup ? 1 : 0,
      dailyGoal: body.dailyGoal,
      quitPlanJson: quitPlanJson,
      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 });
    }

    // Parse returned JSON to construct state again
    const rawJson = preferences.quitPlanJson ? JSON.parse(preferences.quitPlanJson) : null;
    const isNewFormat = rawJson && 'nicotine' in rawJson;
    const quitState = isNewFormat ? rawJson : {
      nicotine: preferences.substance === 'nicotine' ? { plan: rawJson, startDate: preferences.trackingStartDate } : { plan: null, startDate: null },
      weed: preferences.substance === 'weed' ? { plan: rawJson, startDate: preferences.trackingStartDate } : { plan: null, startDate: null }
    };

    return NextResponse.json({
      substance: preferences.substance,
      trackingStartDate: preferences.trackingStartDate,
      hasCompletedSetup: !!preferences.hasCompletedSetup,
      dailyGoal: preferences.dailyGoal,
      quitPlan: null,
      quitState,
      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 });
  }
}
