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

// External upload server configuration
const UPLOAD_SERVER_URL = 'http://167.71.224.75:8700';
const UPLOAD_ENDPOINT = `${UPLOAD_SERVER_URL}/upload`;
const DELETE_ENDPOINT = `${UPLOAD_SERVER_URL}/delete`;

// Helper function to upload image to external server
async function uploadToExternalServer(file: File): Promise<string> {
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch(UPLOAD_ENDPOINT, {
      method: 'POST',
      body: formData,
    });
    
    if (!response.ok) {
      const errorText = await response.text();
      console.error('Upload failed:', response.status, errorText);
      throw new Error(`Upload failed: ${response.statusText}`);
    }
    
    const result = await response.json();
    
    if (result.success && result.url) {
      console.log('Image uploaded successfully:', result.url);
      const imageUrl = `https://quality-web-developer.com/dulhe_sahebimages/uploads/${result.filename}`;
      return imageUrl;
    } else if (result.success && result.filename) {
      // Construct URL if only filename is returned
      const imageUrl = `https://quality-web-developer.com/dulhe_sahebimages/uploads/${result.filename}`;
      return imageUrl;
    } else {
      throw new Error(result.error || 'Invalid response from upload server');
    }
  } catch (error) {
    console.error('Error uploading to external server:', error);
    throw new Error('Failed to upload image to external server');
  }
}

// Helper function to delete image from external server
async function deleteFromExternalServer(imageUrl: string): Promise<void> {
  try {
    // Extract filename from URL
    const filename = imageUrl.split('/').pop();
    if (!filename) return;
    
    const response = await fetch(DELETE_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ filename }),
    });
    
    if (!response.ok) {
      console.error('Failed to delete image from external server');
    } else {
      console.log('Image deleted successfully:', filename);
    }
  } catch (error) {
    console.error('Error deleting from external server:', error);
  }
}

// Helper function to upload multiple images
async function uploadMultipleToExternalServer(files: File[]): Promise<{ url: string; sortOrder: number; isPrimary: boolean }[]> {
  const uploadedImages = [];
  
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    try {
      const imageUrl = await uploadToExternalServer(file);
      uploadedImages.push({
        url: imageUrl,
        sortOrder: i,
        isPrimary: i === 0 // First image is primary by default
      });
    } catch (error) {
      console.error(`Failed to upload  ${i + 1} image :`, error);
      throw new Error(`Failed to upload  ${i + 1} image`);
    }
  }
  
  return uploadedImages;
}

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 colorId = searchParams.get('colorId');
    
    let query: any = {};
    if (productId) query.product = productId;
    if (colorId) query.color = colorId;
    
    const colorImages = await ProductColorImage.find(query)
      .populate('product', 'name slug')
      .populate('color', 'name hexCode');
    
    return NextResponse.json({ success: true, data: colorImages });
  } catch (error: any) {
    console.error('Error fetching color images:', error);
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    await dbConnect();
    const formData = await request.formData();
    const productId = formData.get('productId') as string;
    const colorId = formData.get('colorId') as string;
    const files = formData.getAll('images') as File[];
    
    // Validate inputs
    if (!productId || !colorId) {
      return NextResponse.json({ success: false, error: 'Product ID and Color ID are required' }, { status: 400 });
    }
    
    if (!files || files.length === 0) {
      return NextResponse.json({ success: false, error: 'At least one image is required' }, { status: 400 });
    }
    
    // Validate product exists
    const productExists = await Product.findById(productId);
    if (!productExists) {
      return NextResponse.json({ success: false, error: 'Product not found' }, { status: 404 });
    }
    
    // Validate color exists
    const colorExists = await Color.findById(colorId);
    if (!colorExists) {
      return NextResponse.json({ success: false, error: 'Color not found' }, { status: 404 });
    }
    
    // Find existing color image document
    let colorImage = await ProductColorImage.findOne({ product: productId, color: colorId });
    
    // Upload images to external server
    const uploadedImages = await uploadMultipleToExternalServer(files);
    
    // If this is the first set of images for this color, set first as primary
    if (!colorImage || colorImage.images.length === 0) {
      if (uploadedImages.length > 0) {
        uploadedImages[0].isPrimary = true;
      }
    }
    
    if (colorImage) {
      // Add new images to existing document
      colorImage.images.push(...uploadedImages);
      await colorImage.save();
    } else {
      // Create new document
      colorImage = await ProductColorImage.create({
        product: productId,
        color: colorId,
        images: uploadedImages
      });
    }
    
    const populated = await ProductColorImage.findById(colorImage._id)
      .populate('product', 'name slug')
      .populate('color', 'name hexCode');
    
    return NextResponse.json({ success: true, data: populated }, { status: 201 });
  } catch (error: any) {
    console.error('Error uploading color images:', error);
    return NextResponse.json({ success: false, error: error.message || 'Failed to upload images' }, { status: 500 });
  }
}

export async function PUT(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    const body = await request.json();
    const { action, imageIndex } = body;
    
    const colorImage = await ProductColorImage.findById(id);
    if (!colorImage) {
      return NextResponse.json({ success: false, error: 'Record not found' }, { status: 404 });
    }
    
    if (action === 'setPrimary') {
      // Update primary image
      colorImage.images = colorImage.images.map((img: any, idx: number) => ({
        ...img,
        isPrimary: idx === imageIndex
      }));
      await colorImage.save();
      
      return NextResponse.json({ success: true, message: 'Primary image updated' });
    }
    
    return NextResponse.json({ success: false, error: 'Invalid action' }, { status: 400 });
  } catch (error: any) {
    console.error('Error updating color images:', 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 { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    const imageUrl = searchParams.get('imageUrl');
    
    if (!id || !imageUrl) {
      return NextResponse.json({ success: false, error: 'ID and Image URL are required' }, { status: 400 });
    }
    
    const colorImage = await ProductColorImage.findById(id);
    if (!colorImage) {
      return NextResponse.json({ success: false, error: 'Record not found' }, { status: 404 });
    }
    
    // Check if image exists in the array
    const imageExists = colorImage.images.some((img: { url: string }) => img.url === imageUrl);
    if (!imageExists) {
      return NextResponse.json({ success: false, error: 'Image not found' }, { status: 404 });
    }
    
    // Remove image from array
    colorImage.images = colorImage.images.filter((img: { url: string }) => img.url !== imageUrl);
    
    // If we deleted a primary image and there are images left, set the first as primary
    if (colorImage.images.length > 0 && !colorImage.images.some((img: any) => img.isPrimary)) {
      colorImage.images[0].isPrimary = true;
    }
    
    await colorImage.save();
    
    // Delete image from external server
    await deleteFromExternalServer(imageUrl);
    
    return NextResponse.json({ 
      success: true, 
      message: 'Image deleted successfully',
      remainingImages: colorImage.images.length
    });
  } catch (error: any) {
    console.error('Error deleting color image:', error);
    return NextResponse.json({ success: false, error: error.message }, { status: 500 });
  }
}