import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { verifyAdminAuth } from '@/lib/admin-auth';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const adminUser = await verifyAdminAuth(request);
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const resolvedParams = await params;
    const page = await prisma.page.findUnique({
      where: { id: resolvedParams.id },
      include: {
        creator: { select: { name: true, email: true } },
        updater: { select: { name: true, email: true } }
      }
    });

    if (!page) {
      return NextResponse.json(
        { success: false, error: 'Page not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      data: page
    });
  } catch (error) {
    console.error('Error fetching page:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch page' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const adminUser = await verifyAdminAuth(request);
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const resolvedParams = await params;
    const body = await request.json();
    const {
      title,
      slug,
      content,
      contentType,
      excerpt,
      featuredImage,
      seoTitle,
      seoDescription,
      status,
      showInNavigation,
      showInFooter,
      navigationOrder,
      footerOrder
    } = body;

    // Check if page exists
    const existingPage = await prisma.page.findUnique({
      where: { id: resolvedParams.id }
    });

    if (!existingPage) {
      return NextResponse.json(
        { success: false, error: 'Page not found' },
        { status: 404 }
      );
    }

    // Check if slug is being changed and conflicts with another page
    if (slug && slug !== existingPage.slug) {
      const conflictingPage = await prisma.page.findUnique({
        where: { slug }
      });

      if (conflictingPage && conflictingPage.id !== resolvedParams.id) {
        return NextResponse.json(
          { success: false, error: 'A page with this slug already exists' },
          { status: 400 }
        );
      }
    }

    const updatedPage = await prisma.page.update({
      where: { id: resolvedParams.id },
      data: {
        title,
        slug,
        content,
        contentType,
        excerpt,
        featuredImage,
        seoTitle,
        seoDescription,
        status,
        showInNavigation,
        showInFooter,
        navigationOrder,
        footerOrder,
        updatedBy: adminUser.id,
        publishedAt: status === 'PUBLISHED' && !existingPage.publishedAt
          ? new Date()
          : status === 'PUBLISHED'
          ? existingPage.publishedAt
          : null
      },
      include: {
        creator: { select: { name: true, email: true } },
        updater: { select: { name: true, email: true } }
      }
    });

    return NextResponse.json({
      success: true,
      data: updatedPage
    });
  } catch (error) {
    console.error('Error updating page:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to update page' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const adminUser = await verifyAdminAuth(request);
    if (!adminUser) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const resolvedParams = await params;
    const page = await prisma.page.findUnique({
      where: { id: resolvedParams.id }
    });

    if (!page) {
      return NextResponse.json(
        { success: false, error: 'Page not found' },
        { status: 404 }
      );
    }

    await prisma.page.delete({
      where: { id: resolvedParams.id }
    });

    return NextResponse.json({
      success: true,
      message: 'Page deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting page:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to delete page' },
      { status: 500 }
    );
  }
}