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

// GET
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') || 'asc';

    let query: any = {};

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

    const skip = (page - 1) * limit;
    const sortObj: any = search
      ? { email: 1 }
      : { [sort]: order === 'asc' ? 1 : -1 };

    const subscribers = await NewsLetter.find(query)
      .sort(sortObj)
      .skip(skip)
      .limit(limit);

    const total = await NewsLetter.countDocuments(query);

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

  } catch (error: any) {
    console.error('Error fetching newsletter subscribers:', error);
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to fetch subscribers' },
      { status: 500 }
    );
  }
}

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

    const body  = await request.json();
    const email = body.email?.trim().toLowerCase();

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

    // Check duplicate
    const existing = await NewsLetter.findOne({ email });
    if (existing) {
      return NextResponse.json(
        { success: false, error: 'Email already subscribed' },
        { status: 400 }
      );
    }

    const subscriber = await NewsLetter.create({
      email,
      status: body.status || 'active',
    });

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

  } catch (error: any) {
    console.error('Error creating subscriber:', error);
    if (error.code === 11000) {
      return NextResponse.json(
        { success: false, error: 'Email already subscribed' },
        { status: 400 }
      );
    }
    return NextResponse.json(
      { success: false, error: error.message || 'Failed to subscribe' },
      { status: 500 }
    );
  }
}

// PUT
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: 'Subscriber ID is required' },
        { status: 400 }
      );
    }

    const existing = await NewsLetter.findById(id);
    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'Subscriber not found' },
        { status: 404 }
      );
    }

    const body  = await request.json();
    const email  = body.email?.trim().toLowerCase();
    const status = body.status;

    // Check email not taken by another subscriber
    if (email && email !== existing.email) {
      const emailExists = await NewsLetter.findOne({
        email,
        _id: { $ne: id },
      });
      if (emailExists) {
        return NextResponse.json(
          { success: false, error: 'Email already subscribed' },
          { status: 400 }
        );
      }
    }

    const updateData: any = {};
    if (email)  updateData.email  = email;
    if (status) updateData.status = status;

    const updated = await NewsLetter.findByIdAndUpdate(
      id,
      { $set: updateData },
      { new: true, runValidators: true }
    );

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

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

// DELETE
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: 'Subscriber ID is required' },
        { status: 400 }
      );
    }

    const subscriber = await NewsLetter.findById(id);
    if (!subscriber) {
      return NextResponse.json(
        { success: false, error: 'Subscriber not found' },
        { status: 404 }
      );
    }

    await NewsLetter.findByIdAndDelete(id);

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

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