import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'

export async function POST(req: Request) {
  try {
    const data = await req.json()
    const { code, amount } = data

    if (!code) {
      return NextResponse.json({ error: 'Kode voucher kosong' }, { status: 400 })
    }

    const voucher = await prisma.voucher.findUnique({
      where: { code: code.toUpperCase() }
    })

    if (!voucher) {
      return NextResponse.json({ error: 'Kode voucher tidak ditemukan' }, { status: 404 })
    }

    if (!voucher.isActive) {
      return NextResponse.json({ error: 'Kode voucher sudah tidak aktif' }, { status: 400 })
    }

    if (voucher.maxUses > 0 && voucher.usedCount >= voucher.maxUses) {
      return NextResponse.json({ error: 'Kuota voucher sudah habis' }, { status: 400 })
    }

    if (voucher.expiresAt && new Date() > new Date(voucher.expiresAt)) {
      return NextResponse.json({ error: 'Kode voucher sudah kadaluarsa' }, { status: 400 })
    }

    let discountAmount = 0
    if (voucher.discountType === 'PERCENTAGE') {
      discountAmount = (amount * Number(voucher.discountValue)) / 100
    } else {
      discountAmount = Number(voucher.discountValue)
    }

    // Limit discount to total amount
    if (discountAmount > amount) {
      discountAmount = amount
    }

    return NextResponse.json({
      success: true,
      voucherId: voucher.id,
      code: voucher.code,
      discountAmount,
      finalAmount: amount - discountAmount
    })

  } catch (error) {
    console.error('Failed to validate voucher:', error)
    return NextResponse.json({ error: 'Terjadi kesalahan pada server' }, { status: 500 })
  }
}
