import { NextRequest, NextResponse } from 'next/server'
import pool from '@/lib/db'
import { requireAdmin, logAdminAudit, hashPassword } from '@/lib/admin-auth'

export async function GET(request: NextRequest) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response

  const { rows } = await pool.query(
    `SELECT id, email, name, is_active, last_login_at, created_at, updated_at
     FROM pitch_admins ORDER BY created_at ASC`,
  )
  return NextResponse.json({ admins: rows })
}

export async function POST(request: NextRequest) {
  const guard = await requireAdmin(request)
  if (guard.kind === 'response') return guard.response
  const adminId = guard.kind === 'admin' ? guard.admin.id : null

  const body = await request.json().catch(() => ({}))
  const email = (body.email || '').trim().toLowerCase()
  const name = (body.name || '').trim()
  const password = body.password || ''

  if (!email || !name || !password) {
    return NextResponse.json({ error: 'email, name, password required' }, { status: 400 })
  }
  if (password.length < 12) {
    return NextResponse.json({ error: 'password must be at least 12 characters' }, { status: 400 })
  }

  const hash = await hashPassword(password)

  try {
    const { rows } = await pool.query(
      `INSERT INTO pitch_admins (email, name, password_hash, is_active)
       VALUES ($1, $2, $3, true)
       RETURNING id, email, name, is_active, created_at`,
      [email, name, hash],
    )
    const newAdmin = rows[0]
    await logAdminAudit(adminId, 'admin_created', { email, name, new_admin_id: newAdmin.id }, request)
    return NextResponse.json({ admin: newAdmin })
  } catch (err) {
    const e = err as { code?: string }
    if (e.code === '23505') {
      return NextResponse.json({ error: 'Email already exists' }, { status: 409 })
    }
    throw err
  }
}
