import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'

// Product schema
const ProductSchema = z.object({
  name: z.string().min(1),
  description: z.string().min(1),
  price: z.number().positive(),
  category: z.string().min(1),
  image: z.string().optional(),
  features: z.array(z.string()),
  isActive: z.boolean().default(true),
  stock: z.number().int().min(0).optional(),
  tags: z.array(z.string()).optional()
})

// GET - Fetch all products or specific product
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const productId = searchParams.get('id')
    
    // Verify admin authentication
    const isAuthenticated = await verifyAdminAuth(request)
    if (!isAuthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    if (productId) {
      // Return specific product
      const product = {
        id: productId,
        name: 'Comprehensive Auto Insurance',
        description: 'Full coverage auto insurance with comprehensive benefits',
        price: 150000,
        category: 'Motor Insurance',
        image: '/placeholder.jpg',
        features: ['Accident Coverage', 'Theft Protection', '24/7 Support'],
        isActive: true,
        stock: 100,
        tags: ['popular', 'recommended'],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      return NextResponse.json(product)
    }

    // Return all products (mock data)
    const products = [
      {
        id: '1',
        name: 'Basic Auto Insurance',
        description: 'Essential auto insurance coverage',
        price: 75000,
        category: 'Motor Insurance',
        image: '/placeholder.jpg',
        features: ['Third Party Coverage', 'Basic Support'],
        isActive: true,
        stock: 50,
        tags: ['basic'],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      },
      {
        id: '2',
        name: 'Comprehensive Auto Insurance',
        description: 'Full coverage auto insurance with comprehensive benefits',
        price: 150000,
        category: 'Motor Insurance',
        image: '/placeholder.jpg',
        features: ['Accident Coverage', 'Theft Protection', '24/7 Support'],
        isActive: true,
        stock: 100,
        tags: ['popular', 'recommended'],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      },
      {
        id: '3',
        name: 'Home Insurance',
        description: 'Protect your home and belongings',
        price: 200000,
        category: 'Property Insurance',
        image: '/placeholder.jpg',
        features: ['Fire Coverage', 'Burglary Protection', 'Natural Disaster'],
        isActive: true,
        stock: 75,
        tags: ['home', 'property'],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    ]

    return NextResponse.json({ products, total: products.length })
  } catch (error) {
    console.error('Products fetch error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// POST - Create new product
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    
    // Verify admin authentication
    const isAuthenticated = await verifyAdminAuth(request)
    if (!isAuthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Validate the request body
    const validatedProduct = ProductSchema.parse(body)

    // Create new product (mock implementation)
    const newProduct = {
      id: Date.now().toString(),
      ...validatedProduct,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }

    return NextResponse.json(newProduct, { status: 201 })
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Validation failed', details: error.errors }, { status: 400 })
    }
    console.error('Product creation error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// PUT - Update existing product
export async function PUT(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const productId = searchParams.get('id')
    const body = await request.json()
    
    // Verify admin authentication
    const isAuthenticated = await verifyAdminAuth(request)
    if (!isAuthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    if (!productId) {
      return NextResponse.json({ error: 'Product ID required' }, { status: 400 })
    }

    // Validate the request body
    const validatedProduct = ProductSchema.parse(body)

    // Update product (mock implementation)
    const updatedProduct = {
      id: productId,
      ...validatedProduct,
      updatedAt: new Date().toISOString()
    }

    return NextResponse.json(updatedProduct)
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: 'Validation failed', details: error.errors }, { status: 400 })
    }
    console.error('Product update error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// DELETE - Remove product
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const productId = searchParams.get('id')
    
    // Verify admin authentication
    const isAuthenticated = await verifyAdminAuth(request)
    if (!isAuthenticated) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    if (!productId) {
      return NextResponse.json({ error: 'Product ID required' }, { status: 400 })
    }

    // Delete product (mock implementation)
    return NextResponse.json({ success: true, message: `Product ${productId} deleted successfully` })
  } catch (error) {
    console.error('Product deletion error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// Helper function for admin authentication
async function verifyAdminAuth(request: NextRequest): Promise<boolean> {
  try {
    const authHeader = request.headers.get('authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return false
    }

    const token = authHeader.substring(7)
    
    // Simple token validation (replace with proper JWT verification)
    if (token === process.env.ADMIN_TOKEN || token === 'admin-token-placeholder') {
      return true
    }

    return false
  } catch (error) {
    console.error('Auth verification error:', error)
    return false
  }
}