// app/api/banners/route.ts
import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import Banner from '../../src/models/Banner';

// External upload server configuration (same as categories)
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 generate unique slug
async function generateUniqueSlug(title: string, excludeId?: string): Promise<string> {
  let baseSlug = title
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/\s+/g, '-')
    .replace(/--+/g, '-');

  let slug = baseSlug;
  let counter = 1;

  while (true) {
    const existingBanner = await Banner.findOne({
      banner_slug: slug,
      ...(excludeId && { _id: { $ne: excludeId } })
    });

    if (!existingBanner) break;

    slug = `${baseSlug}-${counter}`;
    counter++;
  }

  return slug;
}

// 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);
  }
}

// ✅ GET (Fetch banners with pagination and sorting)
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 search = searchParams.get('search');
    const status = searchParams.get('status');
    const sort = searchParams.get('sort') || 'createdAt';
    const order = searchParams.get('order') || 'desc';

    // ✅ Build query safely
    let query: any = {};

    if (search) {
      query.$or = [
        { banner_title: { $regex: search, $options: 'i' } },
        { banner_slug: { $regex: search, $options: 'i' } }
      ];
    }

    if (status !== null && status !== undefined && status !== 'all') {
      query.status = status === 'true';
    }

    const skip = (page - 1) * limit;

    // Create sort object
    const sortOptions: any = {};
    if (search) {
      // Always sort alphabetically when searching
      sortOptions.banner_title = 1;
    }
    else if (sort === 'createdAt') {
      sortOptions.createdAt = order === 'asc' ? 1 : -1;
    } else if (sort === 'banner_title') {
      sortOptions.banner_title = order === 'asc' ? 1 : -1;
    } else if (sort === 'status') {
      sortOptions.status = order === 'asc' ? 1 : -1;
    } else {
      sortOptions.createdAt = -1;
    }

    // ✅ FETCH BANNERS
    const banners = await Banner.find(query)
      .sort(sortOptions)
      .skip(skip)
      .limit(limit);

    const total = await Banner.countDocuments(query);

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

  } catch (error: any) {
    console.error('Error fetching banners:', error);

    return NextResponse.json(
      {
        success: false,
        error: error.message || 'Failed to fetch banners'
      },
      { status: 500 }
    );
  }
}

// ✅ POST (Create banner)
export async function POST(request: NextRequest) {
  try {
    await dbConnect();

    const contentType = request.headers.get('content-type') || '';

    if (!contentType.includes('multipart/form-data')) {
      return NextResponse.json(
        { success: false, error: 'Content-Type must be multipart/form-data' },
        { status: 400 }
      );
    }

    const formData = await request.formData();
    const banner_title = formData.get('banner_title') as string;
    const banner_description = formData.get('banner_description') as string;
    const status = formData.get('status') === 'true';
    const banner_image = formData.get('banner_image') as File;

    // Validation
    if (!banner_title?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Banner title is required' },
        { status: 400 }
      );
    }

    if (!banner_image) {
      return NextResponse.json(
        { success: false, error: 'Banner image is required' },
        { status: 400 }
      );
    }

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
    if (!allowedTypes.includes(banner_image.type)) {
      return NextResponse.json(
        { success: false, error: 'Invalid file type. Only JPEG, PNG, WebP, and GIF are allowed.' },
        { status: 400 }
      );
    }

    // Validate file size (5MB max)
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (banner_image.size > maxSize) {
      return NextResponse.json(
        { success: false, error: 'File too large. Maximum size is 5MB.' },
        { status: 400 }
      );
    }

    // Upload image to external server
    let imageUrl = '';
    try {
      imageUrl = await uploadToExternalServer(banner_image);
    } catch (uploadError) {
      console.error('Upload error:', uploadError);
      return NextResponse.json(
        { success: false, error: 'Failed to upload image to server' },
        { status: 500 }
      );
    }

    // Generate unique slug
    const banner_slug = await generateUniqueSlug(banner_title);

    // Create banner
    const banner = await Banner.create({
      banner_title: banner_title.trim(),
      banner_slug,
      banner_description: banner_description?.trim() || '',
      banner_image: imageUrl,
      status
    });

    return NextResponse.json({
      success: true,
      data: banner,
      message: 'Banner created successfully'
    });

  } catch (error: any) {
    console.error('Error creating banner:', error);

    return NextResponse.json(
      { success: false, error: error.message || 'Failed to create banner' },
      { status: 500 }
    );
  }
}

// ✅ PUT (Update banner)
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: 'Banner ID is required' },
        { status: 400 }
      );
    }

    const contentType = request.headers.get('content-type') || '';

    if (!contentType.includes('multipart/form-data')) {
      return NextResponse.json(
        { success: false, error: 'Content-Type must be multipart/form-data' },
        { status: 400 }
      );
    }

    const formData = await request.formData();
    const banner_title = formData.get('banner_title') as string;
    const banner_description = formData.get('banner_description') as string;
    const status = formData.get('status') === 'true';
    const banner_image = formData.get('banner_image') as File | null;

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

    // Validation
    if (!banner_title?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Banner title is required' },
        { status: 400 }
      );
    }

    let imageUrl = existingBanner.banner_image;

    // Handle new image upload
    if (banner_image && banner_image.size > 0) {
      // Validate file type
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
      if (!allowedTypes.includes(banner_image.type)) {
        return NextResponse.json(
          { success: false, error: 'Invalid file type. Only JPEG, PNG, WebP, and GIF are allowed.' },
          { status: 400 }
        );
      }

      // Validate file size (5MB max)
      const maxSize = 5 * 1024 * 1024;
      if (banner_image.size > maxSize) {
        return NextResponse.json(
          { success: false, error: 'File too large. Maximum size is 5MB.' },
          { status: 400 }
        );
      }

      // Delete old image from external server if exists
      if (existingBanner.banner_image && existingBanner.banner_image.includes('quality-web-developer.com')) {
        await deleteFromExternalServer(existingBanner.banner_image);
      }
      
      // Upload new image to external server
      try {
        imageUrl = await uploadToExternalServer(banner_image);
      } catch (uploadError) {
        console.error('Upload error:', uploadError);
        return NextResponse.json(
          { success: false, error: 'Failed to upload image to server' },
          { status: 500 }
        );
      }
    }

    // Generate unique slug if title changed
    let banner_slug = existingBanner.banner_slug;
    if (banner_title.trim() !== existingBanner.banner_title) {
      banner_slug = await generateUniqueSlug(banner_title, id);
    }

    // Update banner
    const updatedBanner = await Banner.findByIdAndUpdate(
      id,
      {
        banner_title: banner_title.trim(),
        banner_slug,
        banner_description: banner_description?.trim() || '',
        banner_image: imageUrl,
        status
      },
      { new: true, runValidators: true }
    );

    return NextResponse.json({
      success: true,
      data: updatedBanner,
      message: 'Banner updated successfully'
    });

  } catch (error: any) {
    console.error('Error updating banner:', error);

    return NextResponse.json(
      { success: false, error: error.message || 'Failed to update banner' },
      { status: 500 }
    );
  }
}

// ✅ DELETE (Delete banner)
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: 'Banner ID is required' },
        { status: 400 }
      );
    }

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

    // Delete image from external server if exists
    if (banner.banner_image && banner.banner_image.includes('quality-web-developer.com')) {
      await deleteFromExternalServer(banner.banner_image);
    }

    await Banner.findByIdAndDelete(id);

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

  } catch (error: any) {
    console.error('Error deleting banner:', error);
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to delete banner' },
      { status: 500 }
    );
  }
}