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

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

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 all landing pages
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const activeOnly = searchParams.get('activeOnly') === 'true'
    const type = searchParams.get('type')

    let whereClause: any = {}
    
    if (activeOnly) {
      whereClause.isActive = true
    }
    
    if (type) {
      whereClause.type = type.toUpperCase()
    }

    const landingPages = await db.landingPage.findMany({
      where: whereClause,
      orderBy: [
        { isDefault: 'desc' },
        { isActive: 'desc' },
        { createdAt: 'desc' }
      ]
    })

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

// POST create new landing page
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const validatedData = createLandingPageSchema.parse(body)

    // Check if slug already exists
    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
    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 },
        data: { isDefault: false }
      })
    }

    // If setting as active, deactivate others (optional - you can have multiple active)
    if (validatedData.isActive) {
      // Uncomment this if you want only one active at a time
      // await db.landingPage.updateMany({
      //   where: { isActive: true },
      //   data: { isActive: false }
      // })
    }

    const landingPage = await db.landingPage.create({
      data: validatedData
    })

    return NextResponse.json({
      success: true,
      data: landingPage,
      message: 'Landing page created successfully'
    })
  } catch (error) {
    console.error('Error creating 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 create landing page' },
      { status: 500 }
    )
  }
}