import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";

// GET - Fetch all active posters
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const position = searchParams.get("position");
    const active = searchParams.get("active") !== "false";

    const collection = await getCollection("posters");
    
    const query: any = {};
    if (active) {
      query.active = true;
      // Check if poster is within date range
      query.$or = [
        { startDate: { $exists: false } },
        { startDate: { $lte: new Date() } },
      ];
      query.$and = [
        {
          $or: [
            { endDate: { $exists: false } },
            { endDate: { $gte: new Date() } },
          ],
        },
      ];
    }
    
    if (position) {
      query.position = position;
    }

    const posters = await collection
      .find(query)
      .sort({ order: 1, createdAt: -1 })
      .toArray();

    // Convert _id to string
    const postersWithStringId = posters.map((poster) => ({
      ...poster,
      _id: poster._id.toString(),
    }));

    return NextResponse.json({ posters: postersWithStringId });
  } catch (error) {
    console.error("Error fetching posters:", error);
    return NextResponse.json(
      { error: "Failed to fetch posters" },
      { status: 500 }
    );
  }
}

// POST - Create a new poster
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const collection = await getCollection("posters");

    const posterData = {
      title: body.title || "",
      description: body.description || "",
      image: body.image || "",
      link: body.link || "",
      position: body.position || "home-top",
      active: body.active !== undefined ? body.active : true,
      order: body.order || 0,
      startDate: body.startDate ? new Date(body.startDate) : undefined,
      endDate: body.endDate ? new Date(body.endDate) : undefined,
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await collection.insertOne(posterData);

    return NextResponse.json({
      success: true,
      poster: {
        ...posterData,
        _id: result.insertedId.toString(),
      },
    });
  } catch (error) {
    console.error("Error creating poster:", error);
    return NextResponse.json(
      { error: "Failed to create poster" },
      { status: 500 }
    );
  }
}

