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

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

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

  const { id, otherId } = await ctx.params

  // Verify both versions exist
  const [vA, vB] = await Promise.all([
    pool.query(`SELECT id, name, status, created_at FROM pitch_versions WHERE id = $1`, [id]),
    pool.query(`SELECT id, name, status, created_at FROM pitch_versions WHERE id = $1`, [otherId]),
  ])
  if (vA.rows.length === 0 || vB.rows.length === 0) {
    return NextResponse.json({ error: 'One or both versions not found' }, { status: 404 })
  }

  const [dataA, dataB] = await Promise.all([
    loadVersionData(id),
    loadVersionData(otherId),
  ])

  const diffs = VERSION_TABLES.map(tableName =>
    diffTable(tableName, dataA[tableName] || [], dataB[tableName] || [])
  ).filter(d => d.hasChanges)

  return NextResponse.json({
    versionA: vA.rows[0],
    versionB: vB.rows[0],
    diffs,
    total_changes: diffs.reduce((sum, d) => sum + d.rows.filter(r => r.status !== 'unchanged').length, 0),
  })
}
