import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { z } from 'zod'
import prisma from '@/lib/prisma'
import { authOptions } from '@/lib/auth'
import { slugify } from '@/lib/utils'

const productSchema = z.object({
  name: z.string().min(2),
  description: z.string().optional(),
  price: z.number().positive(),
  stock: z.number().int().min(0).default(0),
  type: z.enum(['AUTO', 'MANUAL']),
  thumbnail: z.string().optional(),
  features: z.array(z.string()).optional(),
  isActive: z.boolean().default(true),
  sortOrder: z.number().int().default(0),
})

export async function GET(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  const products = await prisma.digitalProduct.findMany({
    include: { _count: { select: { accounts: { where: { status: 'AVAILABLE' } } } } },
    orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
  })
  return NextResponse.json({ products })
}

export async function POST(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  try {
    const body = await req.json()
    const data = productSchema.parse(body)

    const product = await prisma.digitalProduct.create({
      data: {
        ...data,
        slug: slugify(data.name),
        features: data.features ? JSON.stringify(data.features) : null,
      },
    })
    return NextResponse.json({ product }, { status: 201 })
  } catch (error) {
    if (error instanceof z.ZodError) return NextResponse.json({ error: error.errors[0].message }, { status: 400 })
    return NextResponse.json({ error: 'Gagal membuat produk' }, { status: 500 })
  }
}
export async function PUT(req: NextRequest) {
  const session = await getServerSession(authOptions)
  if (session?.user?.role !== 'ADMIN') return NextResponse.json({ error: 'Forbidden' }, { status: 403 })

  try {
    const body = await req.json()
    const { id, ...updateData } = body
    if (!id) return NextResponse.json({ error: 'Product ID is required' }, { status: 400 })

    const data = productSchema.parse(updateData)

    const product = await prisma.digitalProduct.update({
      where: { id },
      data: {
        ...data,
        slug: slugify(data.name),
        features: data.features ? JSON.stringify(data.features) : null,
      },
    })
    return NextResponse.json({ product }, { status: 200 })
  } catch (error) {
    if (error instanceof z.ZodError) return NextResponse.json({ error: error.errors[0].message }, { status: 400 })
    return NextResponse.json({ error: 'Gagal update produk' }, { status: 500 })
  }
}
