import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { ContactUs } from '@/models/ContactUs';
import { requireAdmin } from '@/lib/auth';

// PATCH /api/admin/contacts/[id] - Update contact submission status / notes
export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const { id } = await params;
    const body = await req.json();

    const { status, adminNotes } = body;

    const contact = await ContactUs.findById(id);
    if (!contact) {
      return NextResponse.json({ success: false, error: 'Contact submission not found' }, { status: 404 });
    }

    if (status) {
      if (!['unread', 'read', 'replied', 'archived'].includes(status)) {
        return NextResponse.json({ success: false, error: 'Invalid status value' }, { status: 400 });
      }
      contact.status = status;
    }

    if (adminNotes !== undefined) {
      contact.adminNotes = adminNotes;
    }

    await contact.save();

    return NextResponse.json({
      success: true,
      message: 'Contact submission updated successfully',
      contact,
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error updating contact submission' },
      { status: 500 }
    );
  }
}

// DELETE /api/admin/contacts/[id] - Delete contact submission
export async function DELETE(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const { id } = await params;

    const contact = await ContactUs.findByIdAndDelete(id);
    if (!contact) {
      return NextResponse.json({ success: false, error: 'Contact submission not found' }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: 'Contact submission deleted successfully',
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error deleting contact submission' },
      { status: 500 }
    );
  }
}
