import { NextRequest, NextResponse } from "next/server";
import { checkRateLimit } from "@/lib/rate-limiter";
import {
  getAvailability,
  CreateEventRequest,
  createEvent,
} from "@/infrastructure/external/calendar";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    // Validate required fields
    if (!body.startDate || !body.endDate) {
      return NextResponse.json({ error: "Start date and end date are required" }, { status: 400 });
    }

    const startDate = new Date(body.startDate);
    const endDate = new Date(body.endDate);

    // Validate dates
    if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
      return NextResponse.json({ error: "Invalid date format" }, { status: 400 });
    }

    // Validate date range (max 7 days ahead)
    const now = new Date();
    const maxDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

    if (startDate < now || endDate > maxDate) {
      return NextResponse.json(
        { error: "Date range must be between now and 7 days ahead" },
        { status: 400 }
      );
    }

    if (startDate >= endDate) {
      return NextResponse.json({ error: "End date must be after start date" }, { status: 400 });
    }

    const ip =
      request.ip ||
      request.headers.get("x-forwarded-for")?.split(",")[0] ||
      request.headers.get("x-real-ip") ||
      "unknown";

    // Check rate limit by IP
    const ipLimit = await checkRateLimit(ip, "ip");
    if (!ipLimit.success) {
      return NextResponse.json(
        {
          error: "Too many requests",
          limit: ipLimit.limit,
          remaining: ipLimit.remaining,
          resetTime: ipLimit.resetTime,
        },
        {
          status: 429,
          headers: {
            "X-RateLimit-Limit": ipLimit.limit.toString(),
            "X-RateLimit-Remaining": ipLimit.remaining.toString(),
            "X-RateLimit-Reset": ipLimit.resetTime.toISOString(),
            "Retry-After": Math.ceil((ipLimit.resetTime.getTime() - Date.now()) / 1000).toString(),
          },
        }
      );
    }

    // Get availability from Google Calendar
    const slots = await getAvailability({ startDate, endDate });

    // Filter to show only business hours (9:00 - 19:00, Mon-Fri)
    const businessHoursSlots = slots.filter((slot) => {
      const hour = slot.startTime.getHours();
      const dayOfWeek = slot.startTime.getDay();

      // Only Monday-Friday
      if (dayOfWeek === 0 || dayOfWeek === 6) return false;

      // Business hours: 9:00 - 19:00
      return hour >= 9 && hour < 19;
    });

    // Rate limit headers for successful response
    const headers = {
      "X-RateLimit-Limit": ipLimit.limit.toString(),
      "X-RateLimit-Remaining": ipLimit.remaining.toString(),
      "X-RateLimit-Reset": ipLimit.resetTime.toISOString(),
    };

    return NextResponse.json(
      {
        success: true,
        availability: businessHoursSlots,
        totalSlots: slots.length,
        businessHoursSlots: businessHoursSlots.length,
        dateRange: {
          start: startDate.toISOString(),
          end: endDate.toISOString(),
        },
      },
      { headers }
    );
  } catch (error) {
    console.error("Get availability error:", error);
    return NextResponse.json(
      {
        error: "Internal server error",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}
