import { NextRequest, NextResponse } from 'next/server';
import { trackingLimiter } from '@/lib/middleware/rateLimiter';

/**
 * Feeding tracking endpoint with rate limiting
 * Limited to 30 requests per minute (reasonable for frequent tracking)
 */
export async function POST(request: NextRequest) {
  // Apply rate limiting
  const rateLimitResult = await trackingLimiter(request);
  if (rateLimitResult) return rateLimitResult;

  try {
    const body = await request.json();
    const { childId, type, amount, unit, startTime, endTime, notes } = body;

    // TODO: Implement actual tracking logic
    // This is a placeholder - actual tracking will be handled by backend

    // For now, forward to backend API
    const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3020';
    const response = await fetch(`${backendUrl}/api/v1/tracking/feeding`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // Forward auth token from client
        Authorization: request.headers.get('Authorization') || '',
      },
      body: JSON.stringify({ childId, type, amount, unit, startTime, endTime, notes }),
    });

    const data = await response.json();

    if (!response.ok) {
      return NextResponse.json(data, { status: response.status });
    }

    return NextResponse.json(data, { status: 201 });
  } catch (error) {
    console.error('[Tracking] Feeding error:', error);
    return NextResponse.json(
      {
        error: 'TRACKING_FEEDING_FAILED',
        message: 'Failed to save feeding record. Please try again.',
      },
      { status: 500 }
    );
  }
}

/**
 * Get feeding history with rate limiting
 */
export async function GET(request: NextRequest) {
  // Apply rate limiting
  const rateLimitResult = await trackingLimiter(request);
  if (rateLimitResult) return rateLimitResult;

  try {
    const { searchParams } = new URL(request.url);
    const childId = searchParams.get('childId');
    const startDate = searchParams.get('startDate');
    const endDate = searchParams.get('endDate');

    // For now, forward to backend API
    const backendUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3020';
    const queryString = new URLSearchParams({
      ...(childId && { childId }),
      ...(startDate && { startDate }),
      ...(endDate && { endDate }),
    }).toString();

    const response = await fetch(`${backendUrl}/api/v1/tracking/feeding?${queryString}`, {
      method: 'GET',
      headers: {
        // Forward auth token from client
        Authorization: request.headers.get('Authorization') || '',
      },
    });

    const data = await response.json();

    if (!response.ok) {
      return NextResponse.json(data, { status: response.status });
    }

    return NextResponse.json(data, { status: 200 });
  } catch (error) {
    console.error('[Tracking] Get feeding history error:', error);
    return NextResponse.json(
      {
        error: 'TRACKING_FEEDING_GET_FAILED',
        message: 'Failed to retrieve feeding history. Please try again.',
      },
      { status: 500 }
    );
  }
}
