import { NextRequest, NextResponse } from 'next/server'
import { seriesGenerator } from '@/services/series-generator'

export interface GenerateSeriesRequest {
  basePrompt: string
  config: {
    title: string
    description: string
    imageCount: number
    style: string
  }
  characters?: Array<{
    name: string
    description: string
    features: any
  }>
  items?: Array<{
    name: string
    description: string
    features: any
  }>
}

export interface GenerateSeriesResponse {
  seriesId: string
  config: any
  estimatedTime: number
  status: 'pending' | 'generating' | 'completed' | 'error'
}

export async function POST(request: NextRequest) {
  try {
    const body: GenerateSeriesRequest = await request.json()
    
    const { basePrompt, config, characters = [], items = [] } = body

    if (!basePrompt || !config || !config.title || !config.description) {
      return NextResponse.json(
        { error: 'Missing required fields: basePrompt, config.title, config.description' },
        { status: 400 }
      )
    }

    if (config.imageCount < 1 || config.imageCount > 30) {
      return NextResponse.json(
        { error: 'Image count must be between 1 and 30' },
        { status: 400 }
      )
    }

    // Create the series
    const series = await seriesGenerator.createSeries(
      basePrompt,
      config,
      characters,
      items
    )

    // Simulate image generation (in production, this would trigger actual generation)
    const estimatedTime = Math.max(30, config.imageCount * 10) // 10-30 seconds per image

    return NextResponse.json({
      seriesId: series.id,
      config: series.config,
      estimatedTime,
      status: 'pending',
    })

  } catch (error) {
    console.error('Series generation error:', error)
    return NextResponse.json(
      { error: 'Failed to generate series' },
      { status: 500 }
    )
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const seriesId = searchParams.get('seriesId')

    if (!seriesId) {
      return NextResponse.json(
        { error: 'seriesId parameter is required' },
        { status: 400 }
      )
    }

    const series = seriesGenerator.getSeries(seriesId)

    if (!series) {
      return NextResponse.json(
        { error: 'Series not found' },
        { status: 404 }
      )
    }

    // Calculate generation status
    const imageCount = series.images.length
    const totalImages = series.config.imageCount
    const progressPercentage = Math.round((imageCount / totalImages) * 100)

    let status: 'pending' | 'generating' | 'completed' | 'error' = 'pending'
    if (imageCount === 0) {
      status = 'pending'
    } else if (imageCount < totalImages) {
      status = 'generating'
    } else if (imageCount === totalImages) {
      status = 'completed'
    }

    return NextResponse.json({
      seriesId: series.id,
      config: series.config,
      images: series.images,
      progress: {
        current: imageCount,
        total: totalImages,
        percentage: progressPercentage,
      },
      status,
      createdAt: series.createdAt,
    })

  } catch (error) {
    console.error('Get series error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const seriesId = searchParams.get('seriesId')

    if (!seriesId) {
      return NextResponse.json(
        { error: 'seriesId parameter is required' },
        { status: 400 }
      )
    }

    const success = seriesGenerator.deleteSeries(seriesId)

    if (!success) {
      return NextResponse.json(
        { error: 'Series not found' },
        { status: 404 }
      )
    }

    return NextResponse.json({
      success: true,
      message: 'Series deleted successfully',
    })

  } catch (error) {
    console.error('Delete series error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}