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

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

  try {
    const accounts = await prisma.productAccount.findMany({
      where: { productId: params.id, status: 'AVAILABLE' },
      orderBy: { createdAt: 'desc' },
    })
    return NextResponse.json({ accounts })
  } catch (error) {
    return NextResponse.json({ error: 'Gagal memuat akun' }, { status: 500 })
  }
}

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

  try {
    const { accountsText } = await req.json()
    if (!accountsText) return NextResponse.json({ error: 'Data akun tidak boleh kosong' }, { status: 400 })

    // Parse accountsText format: email:password
    const lines = accountsText.split('\n').map((line: string) => line.trim()).filter(Boolean)
    const newAccounts = []

    for (const line of lines) {
      const parts = line.split(':')
      if (parts.length >= 2) {
        newAccounts.push({
          productId: params.id,
          email: parts[0].trim(),
          password: parts.slice(1).join(':').trim(), // In case password has ':'
        })
      }
    }

    if (newAccounts.length === 0) {
      return NextResponse.json({ error: 'Format salah. Gunakan format email:password' }, { status: 400 })
    }

    const created = await prisma.productAccount.createMany({
      data: newAccounts,
      skipDuplicates: true,
    })

    // Update main product stock count
    await prisma.digitalProduct.update({
      where: { id: params.id },
      data: { stock: { increment: created.count } },
    })

    return NextResponse.json({ message: `Berhasil menambahkan ${created.count} akun`, count: created.count }, { status: 201 })
  } catch (error: any) {
    console.error('[ADD ACCOUNTS]', error)
    return NextResponse.json({ error: error.message || 'Gagal menambahkan akun' }, { status: 500 })
  }
}

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

  try {
    const { searchParams } = new URL(req.url)
    const accountId = searchParams.get('accountId')
    
    if (!accountId) return NextResponse.json({ error: 'Account ID required' }, { status: 400 })

    await prisma.productAccount.delete({
      where: { id: accountId },
    })

    // Update main product stock count
    await prisma.digitalProduct.update({
      where: { id: params.id },
      data: { stock: { decrement: 1 } },
    })

    return NextResponse.json({ message: 'Akun berhasil dihapus' })
  } catch (error) {
    return NextResponse.json({ error: 'Gagal menghapus akun' }, { status: 500 })
  }
}
