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

interface RouteContext {
  params: Promise<{ id: string }>
}

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

  const { id } = await ctx.params

  await runDataCleanup()

  const [investor, sessions, snapshots, audit] = await Promise.all([
    pool.query(
      `SELECT i.id, i.email, i.name, i.company, i.status, i.last_login_at, i.login_count,
              i.created_at, i.updated_at, i.first_activity_at, i.data_masked_at,
              i.assigned_version_id, i.is_showcase, i.preferred_lang,
              v.name AS version_name, v.status AS version_status
       FROM pitch_investors i
       LEFT JOIN pitch_versions v ON v.id = i.assigned_version_id
       WHERE i.id = $1`,
      [id],
    ),
    pool.query(
      `SELECT id, ip_address, user_agent, expires_at, revoked, created_at
       FROM pitch_sessions WHERE investor_id = $1
       ORDER BY created_at DESC LIMIT 50`,
      [id],
    ),
    pool.query(
      `SELECT id, scenario_id, label, is_latest, created_at
       FROM pitch_investor_snapshots WHERE investor_id = $1
       ORDER BY created_at DESC LIMIT 50`,
      [id],
    ),
    pool.query(
      `SELECT a.id, a.action, a.created_at, a.details, a.ip_address, a.slide_id,
              ad.email AS admin_email, ad.name AS admin_name
       FROM pitch_audit_logs a
       LEFT JOIN pitch_admins ad ON ad.id = a.admin_id
       WHERE a.investor_id = $1 OR a.target_investor_id = $1
       ORDER BY a.created_at DESC LIMIT 100`,
      [id],
    ),
  ])

  if (investor.rows.length === 0) {
    return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
  }

  return NextResponse.json({
    investor: investor.rows[0],
    sessions: sessions.rows,
    snapshots: snapshots.rows,
    audit: audit.rows,
  })
}

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

  const { id } = await ctx.params
  const body = await request.json().catch(() => ({}))
  const { name, company, assigned_version_id, is_showcase, preferred_lang } = body

  if (name === undefined && company === undefined && assigned_version_id === undefined && is_showcase === undefined && preferred_lang === undefined) {
    return NextResponse.json({ error: 'name, company, assigned_version_id, is_showcase, or preferred_lang required' }, { status: 400 })
  }

  const before = await pool.query(
    `SELECT name, company, assigned_version_id, is_showcase, preferred_lang FROM pitch_investors WHERE id = $1`,
    [id],
  )
  if (before.rows.length === 0) {
    return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
  }

  // Validate version exists and is committed (if assigning)
  if (assigned_version_id !== undefined && assigned_version_id !== null) {
    const ver = await pool.query(
      `SELECT id, status FROM pitch_versions WHERE id = $1`,
      [assigned_version_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: 'Can only assign committed versions' }, { status: 400 })
    }
  }

  // Use null to clear version assignment, undefined to leave unchanged
  const versionValue = assigned_version_id === undefined ? before.rows[0].assigned_version_id : (assigned_version_id || null)
  const showcaseValue = is_showcase !== undefined ? Boolean(is_showcase) : before.rows[0].is_showcase
  const langValue = preferred_lang === 'en' || preferred_lang === 'de' ? preferred_lang : before.rows[0].preferred_lang

  const { rows } = await pool.query(
    `UPDATE pitch_investors SET
       name = COALESCE($1, name),
       company = COALESCE($2, company),
       assigned_version_id = $4,
       is_showcase = $5,
       preferred_lang = $6,
       updated_at = NOW()
     WHERE id = $3
     RETURNING id, email, name, company, status, assigned_version_id, is_showcase, preferred_lang`,
    [name ?? null, company ?? null, id, versionValue, showcaseValue, langValue],
  )

  const action = assigned_version_id !== undefined && assigned_version_id !== before.rows[0].assigned_version_id
    ? 'investor_version_assigned'
    : 'investor_edited'

  await logAdminAudit(
    adminId,
    action,
    {
      before: before.rows[0],
      after: { name: rows[0].name, company: rows[0].company, assigned_version_id: rows[0].assigned_version_id },
    },
    request,
    id,
  )

  return NextResponse.json({ investor: rows[0] })
}
