// controllers/productSKUController.ts
import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import ProductSKU from '../../src/models/ProductSKU';
import Product from '../../src/models/Product';
import Color from '../../src/models/Color';
import Size from '../../src/models/Size';

export async function GET(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    const { searchParams } = new URL(request.url);
    const productId = searchParams.get('productId');
    
    let query: any = {};
    if (productId) query.product = productId;
    
    const skus = await ProductSKU.find(query)
      .populate('product', 'name slug')
      .populate('color', 'name hexCode')
      .populate('size', 'name')
      .sort({ createdAt: -1 });
    
    return NextResponse.json({ success: true, data: skus });
  } catch (error: any) {
    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 { product, sku, color, size, quantity, price, comparePrice } = body;
    
    // Validation
    if (!product || !sku || !color || !size) {
      return NextResponse.json({ success: false, error: 'Missing required fields' }, { status: 400 });
    }
    
    const productExists = await Product.findById(product);
    if (!productExists) {
      return NextResponse.json({ success: false, error: 'Invalid product' }, { status: 400 });
    }
    
    const colorExists = await Color.findById(color);
    if (!colorExists) {
      return NextResponse.json({ success: false, error: 'Invalid color' }, { status: 400 });
    }
    
    const sizeExists = await Size.findById(size);
    if (!sizeExists) {
      return NextResponse.json({ success: false, error: 'Invalid size' }, { status: 400 });
    }
    
    const productSKU = await ProductSKU.create({
      product,
      sku: sku.toUpperCase().trim(),
      color,
      size,
      quantity: quantity || 0,
      price: price || 0,
      comparePrice
    });
    
    const populated = await ProductSKU.findById(productSKU._id)
      .populate('product', 'name slug')
      .populate('color', 'name hexCode')
      .populate('size', 'name');
    
    return NextResponse.json({ success: true, data: populated }, { status: 201 });
  } catch (error: any) {
    if (error.code === 11000) {
      return NextResponse.json({ success: false, error: 'SKU already exists' }, { 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: 'SKU ID is required' }, { status: 400 });
    }
    
    const body = await request.json();
    
    // Check if SKU exists
    const existingSKU = await ProductSKU.findById(id);
    if (!existingSKU) {
      return NextResponse.json({ success: false, error: 'SKU not found' }, { status: 404 });
    }
    
    // Validate color if provided
    if (body.color) {
      const colorExists = await Color.findById(body.color);
      if (!colorExists) {
        return NextResponse.json({ success: false, error: 'Invalid color' }, { status: 400 });
      }
    }
    
    // Validate size if provided
    if (body.size) {
      const sizeExists = await Size.findById(body.size);
      if (!sizeExists) {
        return NextResponse.json({ success: false, error: 'Invalid size' }, { status: 400 });
      }
    }
    
    // Update SKU
    const updatedSKU = await ProductSKU.findByIdAndUpdate(
      id, 
      {
        ...body,
        sku: body.sku ? body.sku.toUpperCase().trim() : undefined,
      }, 
      { new: true, runValidators: true }
    )
      .populate('product', 'name slug')
      .populate('color', 'name hexCode')
      .populate('size', 'name');
    
    return NextResponse.json({ success: true, data: updatedSKU });
  } catch (error: any) {
    if (error.code === 11000) {
      return NextResponse.json({ success: false, error: 'SKU already exists' }, { 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: 'SKU ID is required' }, { status: 400 });
    }
    
    // Check if SKU exists
    const existingSKU = await ProductSKU.findById(id);
    if (!existingSKU) {
      return NextResponse.json({ success: false, error: 'SKU not found' }, { status: 404 });
    }
    
    // Delete the SKU
    await ProductSKU.findByIdAndDelete(id);
    
    return NextResponse.json({ success: true, message: 'SKU deleted successfully' });
  } catch (error: any) {
    console.error('Error deleting SKU:', error);
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}