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

// External upload server configuration (same as categories and banners)
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 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 existingCMS = await CMS.findOne({
      slug,
      ...(excludeId && { _id: { $ne: excludeId } })
    });

    if (!existingCMS) break;

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

  return slug;
}

// ✅ GET (Fetch CMS pages with pagination, search, 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 = [
        { title: { $regex: search, $options: 'i' } },
        { 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.title = 1;
    }
    else if (sort === 'createdAt') {
      sortOptions.createdAt = order === 'asc' ? 1 : -1;
    } else if (sort === 'title') {
      sortOptions.title = order === 'asc' ? 1 : -1;
    } else if (sort === 'status') {
      sortOptions.status = order === 'asc' ? 1 : -1;
    } else {
      sortOptions.createdAt = -1;
    }

    // Fetch CMS pages
    const cmsPages = await CMS.find(query)
      .sort(sortOptions)
      .skip(skip)
      .limit(limit);

    const total = await CMS.countDocuments(query);

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

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

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

// ✅ POST (Create CMS page)
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 title = formData.get('title') as string;
    const content = formData.get('content') as string;
    const meta_title = formData.get('meta_title') as string;
    const meta_keywords = formData.get('meta_keywords') as string;
    const status = formData.get('status') === 'true';
    const featured_image = formData.get('featured_image') as File;

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

    if (!content?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Content is required' },
        { status: 400 }
      );
    }

    // Generate unique slug
    const slug = await generateUniqueSlug(title);

    // Handle featured image
    let imageUrl = '';
    if (featured_image && featured_image.size > 0) {
      // Validate file type
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
      if (!allowedTypes.includes(featured_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 (featured_image.size > maxSize) {
        return NextResponse.json(
          { success: false, error: 'File too large. Maximum size is 5MB.' },
          { status: 400 }
        );
      }

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

    // Parse meta keywords
    let keywordsArray: string[] = [];
    if (meta_keywords) {
      keywordsArray = meta_keywords.split(',').map(k => k.trim()).filter(k => k.length > 0);
    }

    // Create CMS page
    const cmsPage = await CMS.create({
      title: title.trim(),
      slug,
      content: content.trim(),
      featured_image: imageUrl || undefined,
      meta_title: meta_title?.trim() || undefined,
      meta_keywords: keywordsArray.length > 0 ? keywordsArray : undefined,
      status
    });

    return NextResponse.json({
      success: true,
      data: cmsPage,
      message: 'CMS page created successfully'
    });

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

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

// ✅ PUT (Update CMS page)
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: 'CMS page 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 title = formData.get('title') as string;
    const content = formData.get('content') as string;
    const meta_title = formData.get('meta_title') as string;
    const meta_keywords = formData.get('meta_keywords') as string;
    const status = formData.get('status') === 'true';
    const featured_image = formData.get('featured_image') as File | null;
    const remove_image = formData.get('remove_image') === 'true';

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

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

    if (!content?.trim()) {
      return NextResponse.json(
        { success: false, error: 'Content is required' },
        { status: 400 }
      );
    }

    let imageUrl = existingCMS.featured_image;

    // Handle image removal
    if (remove_image) {
      if (existingCMS.featured_image && existingCMS.featured_image.includes('quality-web-developer.com')) {
        await deleteFromExternalServer(existingCMS.featured_image);
      }
      imageUrl = '';
    }

    // Handle new image upload
    if (featured_image && featured_image.size > 0) {
      // Validate file type
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
      if (!allowedTypes.includes(featured_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 (featured_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 (existingCMS.featured_image && existingCMS.featured_image.includes('quality-web-developer.com')) {
        await deleteFromExternalServer(existingCMS.featured_image);
      }
      
      // Upload new image to external server
      try {
        imageUrl = await uploadToExternalServer(featured_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 slug = existingCMS.slug;
    if (title.trim().toLowerCase() !== existingCMS.title.trim().toLowerCase()) {
      slug = await generateUniqueSlug(title, id);
    }

    // Parse meta keywords
    let keywordsArray: string[] = [];
    if (meta_keywords) {
      keywordsArray = meta_keywords.split(',').map(k => k.trim()).filter(k => k.length > 0);
    }

    // Update CMS page
    const updatedCMS = await CMS.findByIdAndUpdate(
      id,
      {
        title: title.trim(),
        slug,
        content: content.trim(),
        featured_image: imageUrl || undefined,
        meta_title: meta_title?.trim() || undefined,
        meta_keywords: keywordsArray.length > 0 ? keywordsArray : undefined,
        status
      },
      { new: true, runValidators: true }
    );

    return NextResponse.json({
      success: true,
      data: updatedCMS,
      message: 'CMS page updated successfully'
    });

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

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

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

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

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

    await CMS.findByIdAndDelete(id);

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

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