/**
 * GET /api/social/calendar
 * Get calendar events for a month
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { SocialCalendarService } from "@/lib/services/social-calendar.service";
import { calendarQuerySchema } from "@/lib/validators/social-media.validator";
import { logger } from "@/lib/logger";

export async function GET(request: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const sp = request.nextUrl.searchParams;
    const parsed = calendarQuerySchema.safeParse({
      month: sp.get("month"),
      year: sp.get("year"),
      socialAccountId: sp.get("socialAccountId"),
    });

    if (!parsed.success) {
      return NextResponse.json(
        {
          success: false,
          error: parsed.error.errors[0]?.message || "Invalid query",
        },
        { status: 400 },
      );
    }

    const items = await SocialCalendarService.getCalendarEvents(
      session.user.id,
      parsed.data,
    );

    return NextResponse.json({ items, success: true });
  } catch (error) {
    logger.error("Failed to get calendar events", { error });
    return NextResponse.json(
      { success: false, error: "Failed to get calendar" },
      { status: 500 },
    );
  }
}
