import { NextRequest, NextResponse } from "next/server";
import dbConnect from "../../src/lib/mongodb";
import Size from "../../src/models/Size";
import ProductSKU from "../../src/models/ProductSKU";

// In your API route (app/api/sizes/route.ts)
export async function GET(
  request: NextRequest,
  context?: { params: Promise<any> },
) {
  try {
    await dbConnect();

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "10");
    const category = searchParams.get("category");
    const isActive = searchParams.get("isActive");
    const search = searchParams.get("search");
    const sort = searchParams.get("sort") || "createdAt";
    const order = searchParams.get("order") || "desc";

    let query: any = {};

    if (category) {
      query.category = category;
    }

    if (isActive !== null) {
      query.isActive = isActive === "true";
    }

    if (search) {
      query.name = { $regex: search, $options: "i" };
    }

    const skip = (page - 1) * limit;

    // Create sort object
    const sortOptions: any = {};
    if (sort === "createdAt") {
      sortOptions.createdAt = order === "asc" ? 1 : -1;
    } else if (sort === "sortOrder") {
      sortOptions.sortOrder = order === "asc" ? 1 : -1;
    } else {
      sortOptions.name = order === "asc" ? 1 : -1;
    }

    const sizes = await Size.find(query)
      .sort(sortOptions)
      .skip(skip)
      .limit(limit);

    const total = await Size.countDocuments(query);

    return NextResponse.json({
      success: true,
      data: sizes,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    });
  } catch (error: any) {
    console.error("Error fetching sizes:", error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 },
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    await dbConnect();

    const body = await request.json();

    const {
      name,
      sortOrder = 0,
      isActive = true,

      chest,
      shoulder,
      frontLength,
      neck,
      waist,
      hip,
      sleeveLength,
    } = body;

    // ✅ Validate name
    if (!name || name.trim().length === 0) {
      return NextResponse.json(
        { success: false, error: "Size name is required" },
        { status: 400 },
      );
    }

    // ✅ Optional: at least one measurement required
    // if (
    //   chest === undefined &&
    //   shoulder === undefined &&
    //   frontLength === undefined &&
    //   neck === undefined &&
    //   waist === undefined &&
    //   hip === undefined &&
    //   sleeveLength === undefined
    // ) {
    //   return NextResponse.json(
    //     { success: false, error: 'At least one measurement is required' },
    //     { status: 400 }
    //   );
    // }

    // ✅ Create size
    const existing = await Size.findOne({
      $or: [
        { name: { $regex: `^${name}$`, $options: "i" } }, // case insensitive name match
      ],
    });

    if (existing) {
      return NextResponse.json(
        { success: false, error: "Size with this name already exists" },
        { status: 400 },
      );
    }
    const size = await Size.create({
      name: name.trim(),
      sortOrder,
      isActive,

      chest,
      shoulder,
      frontLength,
      neck,
      waist,
      hip,
      sleeveLength,
    });

    return NextResponse.json(
      {
        success: true,
        data: size,
      },
      { status: 201 },
    );
  } catch (error: any) {
    console.error("Error creating size:", error);

    if (error.code === 11000) {
      return NextResponse.json(
        { success: false, error: "Duplicate size entry" },
        { status: 400 },
      );
    }

    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 },
    );
  }
}

export async function PUT(
  request: NextRequest,
  context?: { params: Promise<any> },
) {
  try {
    await dbConnect();

    const url = new URL(request.url);
    const id = url.pathname.split("/").pop();

    if (!id) {
      return NextResponse.json(
        { success: false, error: "Size ID is required" },
        { status: 400 },
      );
    }

    const body = await request.json();

    const {
      name,
      sortOrder = 0,
      isActive = true,

      // ✅ measurements
      chest,
      shoulder,
      frontLength,
      neck,
      waist,
      hip,
      sleeveLength,
    } = body;

    // ✅ Validate name
    if (!name || name.trim().length === 0) {
      return NextResponse.json(
        { success: false, error: "Size name is required" },
        { status: 400 },
      );
    }
    const existing = await Size.findOne({
      _id: { $ne: id }, // exclude current record
      name: { $regex: `^${name.trim()}$`, $options: "i" },
    });

    if (existing) {
      return NextResponse.json(
        {
          success: false,
          error: "Size with this name already exists",
        },
        { status: 400 },
      );
    }

    // ✅ Check if size exists
    const existingSize = await Size.findById(id);
    if (!existingSize) {
      return NextResponse.json(
        { success: false, error: "Size not found" },
        { status: 404 },
      );
    }

    // ✅ Optional: at least one measurement required
    // if (
    //   chest === undefined &&
    //   shoulder === undefined &&
    //   frontLength === undefined &&
    //   neck === undefined &&
    //   waist === undefined &&
    //   hip === undefined &&
    //   sleeveLength === undefined
    // ) {
    //   return NextResponse.json(
    //     { success: false, error: 'At least one measurement is required' },
    //     { status: 400 }
    //   );
    // }

    const updatedSize = await Size.findByIdAndUpdate(
      id,
      {
        name: name.trim(),
        sortOrder,
        isActive,

        chest,
        shoulder,
        frontLength,
        neck,
        waist,
        hip,
        sleeveLength,
      },
      { new: true, runValidators: true },
    );

    return NextResponse.json({
      success: true,
      data: updatedSize,
    });
  } catch (error: any) {
    console.error("Error updating size:", error);

    if (error.code === 11000) {
      return NextResponse.json(
        { success: false, error: "Duplicate size entry" },
        { status: 400 },
      );
    }

    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 },
    );
  }
}

export async function DELETE(
  request: NextRequest,
  context?: { params: Promise<any> },
) {
  try {
    await dbConnect();

    const url = new URL(request.url);
    const id = url.pathname.split("/").pop();

    if (!id) {
      return NextResponse.json(
        { success: false, error: "Size ID is required" },
        { status: 400 },
      );
    }

    // Check if size exists
    const size = await Size.findById(id);
    if (!size) {
      return NextResponse.json(
        { success: false, error: "Size not found" },
        { status: 404 },
      );
    }

    const isUsedInSku = await ProductSKU.findOne({ size: id });

    if (isUsedInSku) {
      return NextResponse.json(
        {
          success: false,
          error:
            "Cannot delete size because it is used in one or more product SKUs",
        },
        { status: 400 },
      );
    }

    await Size.findByIdAndDelete(id);

    return NextResponse.json({
      success: true,
      message: "Size deleted successfully",
    });
  } catch (error: any) {
    console.error("Error deleting size:", error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 },
    );
  }
}
