import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import ProductImage from '../../src/models/ProductImage';
import ProductColor from '../../src/models/ProductColor';
import Product from '../../src/models/Product';

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

    const { searchParams } = new URL(request.url);
    const productId = searchParams.get('productId');
    const productColorId = searchParams.get('productColorId');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');

    let query: any = {};

    if (productId) {
      query.product = productId;
    }

    if (productColorId) {
      query.productColor = productColorId;
    }

    const skip = (page - 1) * limit;

    const productImages = await ProductImage.find(query)
      .populate('product', 'name slug')
      .populate('productColor', 'sku')
      .sort({ sortOrder: 1, createdAt: 1 })
      .skip(skip)
      .limit(limit);

    const total = await ProductImage.countDocuments(query);

    return NextResponse.json({
      success: true,
      data: productImages,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });

  } catch (error: any) {
    console.error('Error fetching product images:', 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 {
      productColor,
      product,
      imageUrl,
      altText,
      sortOrder = 0,
      isActive = true
    } = body;

    // Validation
    if (!productColor || !product || !imageUrl) {
      return NextResponse.json(
        { success: false, error: 'Product Color, Product, and Image URL are required' },
        { status: 400 }
      );
    }

    // Validate product color exists
    const productColorExists = await ProductColor.findById(productColor);
    if (!productColorExists) {
      return NextResponse.json(
        { success: false, error: 'Product Color does not exist' },
        { status: 400 }
      );
    }

    // Validate product exists
    const productExists = await Product.findById(product);
    if (!productExists) {
      return NextResponse.json(
        { success: false, error: 'Product does not exist' },
        { status: 400 }
      );
    }

    const productImage = await ProductImage.create({
      productColor,
      product,
      imageUrl,
      altText,
      sortOrder,
      isActive
    });

    const populatedProductImage = await ProductImage.findById(productImage._id)
      .populate('product', 'name slug')
      .populate('productColor', 'sku');

    return NextResponse.json({
      success: true,
      data: populatedProductImage
    }, { status: 201 });

  } catch (error: any) {
    console.error('Error creating product image:', error);
    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: 'Product Image ID is required' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const {
      imageUrl,
      altText,
      sortOrder,
      isActive
    } = body;

    const productImage = await ProductImage.findByIdAndUpdate(
      id,
      {
        imageUrl,
        altText,
        sortOrder,
        isActive
      },
      { new: true, runValidators: true }
    ).populate('product', 'name slug')
      .populate('productColor', 'sku');

    if (!productImage) {
      return NextResponse.json(
        { success: false, error: 'Product Image not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      data: productImage
    });

  } catch (error: any) {
    console.error('Error updating product image:', error);
    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: 'Product Image ID is required' },
        { status: 400 }
      );
    }

    const productImage = await ProductImage.findByIdAndDelete(id);

    if (!productImage) {
      return NextResponse.json(
        { success: false, error: 'Product Image not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      message: 'Product Image deleted successfully'
    });

  } catch (error: any) {
    console.error('Error deleting product image:', error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  }
}
