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

// GET all sliders
export async function GET() {
  try {
    const sliders = await db.slider.findMany({
      orderBy: [
        { order: 'asc' },
        { createdAt: 'desc' }
      ]
    })

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

// POST create new slider
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { title, subtitle, description, imageFile, imageUrl, linkUrl, displayType, isActive, order } = body

    // Validation - title is now optional, but if displayType is WITH_TEXT, title or subtitle should be provided
    if (displayType === 'WITH_TEXT' && (!title || title.trim() === '') && (!subtitle || subtitle.trim() === '')) {
      return NextResponse.json(
        { success: false, error: 'Title or subtitle is required when display type is "With Text"' },
        { status: 400 }
      )
    }

    // Get the highest order if not provided
    let sliderOrder = order
    if (sliderOrder === undefined || sliderOrder === null) {
      const lastSlider = await db.slider.findFirst({
        orderBy: { order: 'desc' }
      })
      sliderOrder = lastSlider ? lastSlider.order + 1 : 1
    }

    const slider = await db.slider.create({
      data: {
        title: title?.trim() || null,
        subtitle: subtitle?.trim() || null,
        description: description?.trim() || null,
        imageFile: imageFile?.trim() || null,
        imageUrl: imageUrl?.trim() || null,
        linkUrl: linkUrl?.trim() || null,
        displayType: displayType || 'WITH_TEXT',
        isActive: isActive !== undefined ? isActive : true,
        order: sliderOrder
      }
    })

    return NextResponse.json({
      success: true,
      data: slider,
      message: 'Slider created successfully'
    })
  } catch (error) {
    console.error('Error creating slider:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to create slider' },
      { status: 500 }
    )
  }
}