import { NextResponse } from "next/server";
import Model3D from "@/models/Model3D";
import Hotspot from "@/models/Hotspot";

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get("page") || "1", 10);
    const limit = parseInt(searchParams.get("limit") || "10", 10);

    if (page < 1 || limit < 1) {
      return NextResponse.json({ error: "Invalid page or limit" }, { status: 400 });
    }

    const offset = (page - 1) * limit;

    // Fetch models with nested hotspots
    const { rows: models, count: total } = await Model3D.findAndCountAll({
      include: [
        {
          model: Hotspot,
          as: "hotspots",
          attributes: ["id", "position", "normal", "title", "description"],
        },
      ],
      where: { status: 1 }, // Only fetch active models
      distinct: true, // Ensure correct count with joins
      order: [["id", "DESC"]],
      limit,
      offset,
    });

    return NextResponse.json({
      page,
      limit,
      total,
      hasMore: offset + models.length < total,
      data: models,
    });
  } catch (error) {
    console.error("Error fetching models:", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { title, description, speachtext, image, modelSrc, category, program, size, date } = body;

    // Validate required fields
    if (!title || !description || !modelSrc || !category || !program) {
      return NextResponse.json(
        { error: "Missing required fields: title, description, modelSrc, category, program" },
        { status: 400 }
      );
    }

    const newModel = await Model3D.create({
      title,
      description,
      speachtext: speachtext || "",
      image: image || "",
      modelSrc,
      category,
      program,
      size: size || "",
      date: date || new Date().toLocaleDateString(),
      status: 1,
    });

    let modelData = newModel.get({ plain: true }) as unknown as Record<string, unknown>;

    // Ensure hotspots array exists
    if (!modelData.hotspots) {
      modelData.hotspots = [];
    }

    // Fallback: If ID is null or missing, fetch by other attributes
    if (!modelData.id) {
      console.warn("Model ID is null, attempting fallback query with title:", title);
      const foundModel = await Model3D.findOne({
        where: {
          title,
          modelSrc,
          category,
        },
        order: [["id", "DESC"]],
        include: [
          {
            model: Hotspot,
            as: "hotspots",
            attributes: ["id", "position", "normal", "title", "description"],
          },
        ],
      });
      if (foundModel) {
        modelData = foundModel.get({ plain: true }) as unknown as Record<string, unknown>;
        console.log("Fallback query found model with ID:", modelData.id);
      }
    } else {
      // Re-fetch with hotspots included
      const completeModel = await Model3D.findByPk(modelData.id as number, {
        include: [
          {
            model: Hotspot,
            as: "hotspots",
            attributes: ["id", "position", "normal", "title", "description"],
          },
        ],
      });
      if (completeModel) {
        modelData = completeModel.get({ plain: true }) as unknown as Record<string, unknown>;
      }
    }

    // Final safety check to ensure hotspots array exists
    if (!modelData.hotspots) {
      modelData.hotspots = [];
    }

    return NextResponse.json(modelData, { status: 201 });
  } catch (error) {
    console.error("Error creating model:", error);
    return NextResponse.json({ error: "Failed to create model" }, { status: 500 });
  }
}