import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { z } from 'zod'

const updateLandingPageSchema = z.object({
  name: z.string().min(1, 'Name is required').optional(),
  slug: z.string().min(1, 'Slug is required').optional(),
  title: z.string().min(1, 'Title is required').optional(),
  description: z.string().optional(),
  type: z.enum(['CLASSIC', 'MODERN', 'MINIMAL', 'CORPORATE']).optional(),
  path: z.string().min(1, 'Path is required').optional(),
  isActive: z.boolean().optional(),
  isDefault: z.boolean().optional(),
  settings: z.any().optional(),
  metadata: z.any().optional(),
})

// GET landing page by ID
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const landingPage = await db.landingPage.findUnique({
      where: { id: params.id }
    })

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

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

// PUT update landing page
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json()
    const validatedData = updateLandingPageSchema.parse(body)

    // Check if landing page exists
    const existingPage = await db.landingPage.findUnique({
      where: { id: params.id }
    })

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

    // Check if slug already exists (if updating slug)
    if (validatedData.slug && validatedData.slug !== existingPage.slug) {
      const existingSlug = await db.landingPage.findUnique({
        where: { slug: validatedData.slug }
      })

      if (existingSlug) {
        return NextResponse.json(
          { success: false, error: 'Slug already exists' },
          { status: 400 }
        )
      }
    }

    // Check if name already exists (if updating name)
    if (validatedData.name && validatedData.name !== existingPage.name) {
      const existingName = await db.landingPage.findUnique({
        where: { name: validatedData.name }
      })

      if (existingName) {
        return NextResponse.json(
          { success: false, error: 'Name already exists' },
          { status: 400 }
        )
      }
    }

    // If setting as default, unset other defaults
    if (validatedData.isDefault) {
      await db.landingPage.updateMany({
        where: { 
          isDefault: true,
          id: { not: params.id }
        },
        data: { isDefault: false }
      })
    }

    const landingPage = await db.landingPage.update({
      where: { id: params.id },
      data: validatedData
    })

    return NextResponse.json({
      success: true,
      data: landingPage,
      message: 'Landing page updated successfully'
    })
  } catch (error) {
    console.error('Error updating landing page:', error)
    
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { success: false, error: 'Validation failed', details: error.errors },
        { status: 400 }
      )
    }

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

// DELETE landing page
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // Check if landing page exists
    const existingPage = await db.landingPage.findUnique({
      where: { id: params.id }
    })

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

    // Prevent deletion if it's the default page
    if (existingPage.isDefault) {
      return NextResponse.json(
        { success: false, error: 'Cannot delete default landing page' },
        { status: 400 }
      )
    }

    await db.landingPage.delete({
      where: { id: params.id }
    })

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