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

interface Ctx { params: Promise<{ id: string; tableName: string }> }

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

  const { id, tableName } = await ctx.params

  if (!VERSION_TABLES.includes(tableName as VersionTableName)) {
    return NextResponse.json({ error: `Invalid table: ${tableName}` }, { status: 400 })
  }

  const { rows } = await pool.query(
    `SELECT data, updated_at, updated_by FROM pitch_version_data
     WHERE version_id = $1 AND table_name = $2`,
    [id, tableName],
  )

  if (rows.length === 0) {
    return NextResponse.json({ data: [], updated_at: null })
  }

  const data = typeof rows[0].data === 'string' ? JSON.parse(rows[0].data) : rows[0].data
  return NextResponse.json({ data, updated_at: rows[0].updated_at })
}

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

  const { id, tableName } = await ctx.params

  if (!VERSION_TABLES.includes(tableName as VersionTableName)) {
    return NextResponse.json({ error: `Invalid table: ${tableName}` }, { status: 400 })
  }

  // Verify version is a draft
  const ver = await pool.query(`SELECT status FROM pitch_versions WHERE id = $1`, [id])
  if (ver.rows.length === 0) return NextResponse.json({ error: 'Version not found' }, { status: 404 })
  if (ver.rows[0].status === 'committed') {
    return NextResponse.json({ error: 'Cannot edit a committed version' }, { status: 400 })
  }

  const body = await request.json().catch(() => ({}))
  const { data } = body
  if (!Array.isArray(data) && typeof data !== 'object') {
    return NextResponse.json({ error: 'data must be an array or object' }, { status: 400 })
  }

  // Wrap single-record tables in array for consistency
  const normalizedData = Array.isArray(data) ? data : [data]

  await pool.query(
    `INSERT INTO pitch_version_data (version_id, table_name, data, updated_by)
     VALUES ($1, $2, $3, $4)
     ON CONFLICT (version_id, table_name) DO UPDATE SET
       data = $3, updated_at = NOW(), updated_by = $4`,
    [id, tableName, JSON.stringify(normalizedData), adminId],
  )

  await logAdminAudit(adminId, 'version_data_edited', {
    version_id: id,
    table_name: tableName,
  }, request)

  return NextResponse.json({ success: true })
}
