import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import {
  getUsageEntriesD1,
  getUsageEntryD1,
  upsertUsageEntryD1,
  deleteUsageEntryD1
} from '@/lib/d1';

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

    const entries = await getUsageEntriesD1(session.user.id);

    return NextResponse.json(
      entries.map((e) => ({
        date: e.date,
        count: e.count,
        substance: e.substance,
      }))
    );
  } catch (error) {
    console.error('Error fetching usage data:', 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 { date?: string; count?: number; substance?: string };
    const { date, count, substance } = body;

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

    // Add to existing count
    const entry = await upsertUsageEntryD1(session.user.id, date, count, substance, true);

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

    return NextResponse.json({
      date: entry.date,
      count: entry.count,
      substance: entry.substance,
    });
  } catch (error) {
    console.error('Error saving usage entry:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

    const body = await request.json() as { date?: string; count?: number; substance?: string };
    const { date, count, substance } = body;

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

    // Set the exact count (replace, not add)
    const entry = await upsertUsageEntryD1(session.user.id, date, count, substance, false);

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

    return NextResponse.json({
      date: entry.date,
      count: entry.count,
      substance: entry.substance,
    });
  } catch (error) {
    console.error('Error updating usage entry:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

    const { searchParams } = new URL(request.url);
    const date = searchParams.get('date');
    const substance = searchParams.get('substance');

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

    await deleteUsageEntryD1(session.user.id, date, substance);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting usage entry:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
