/**
 * GET /api/route53/zones/:zoneId/records/:recordId/history
 *   Returns the append-only change ledger for a single record (SC-4's
 *   "history is queryable, not just current state" proof). `recordId` is the
 *   URL-encoded `record_key` (`${zoneId}:${name}:${type}:${setIdentifier}`).
 *   requireAuth() gated.
 *
 *   Query params: `?limit=` (default 50, clamped to 1..200).
 */

import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
import type { Route53RecordHistory, Route53HistorySource } from '@/lib/types/route53';

interface HistoryRow {
  id: string;
  zone_id: string;
  record_key: string;
  record_name: string;
  record_type: string;
  change_action: 'create' | 'update' | 'delete';
  before_value: Record<string, unknown> | null;
  after_value: Record<string, unknown> | null;
  source: Route53HistorySource;
  changed_by_user_id: string | null;
  changed_by_email: string | null;
  changed_at: string;
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ zoneId: string; recordId: string }> }
) {
  const { error } = await requireAuth();
  if (error) return error;

  try {
    const { recordId } = await params;
    const recordKey = decodeURIComponent(recordId);

    const url = request.nextUrl;
    const rawLimit = parseInt(url.searchParams.get('limit') ?? '50', 10);
    const limit = Math.min(Math.max(Number.isFinite(rawLimit) ? rawLimit : 50, 1), 200);

    const res = await postgresClient.query<HistoryRow>(
      `SELECT id, zone_id, record_key, record_name, record_type, change_action,
              before_value, after_value, source, changed_by_user_id, changed_by_email, changed_at
         FROM route53_record_history
        WHERE record_key = $1
        ORDER BY changed_at DESC
        LIMIT $2`,
      [recordKey, limit]
    );

    const items: Route53RecordHistory[] = res.rows.map((row) => ({
      id: row.id,
      zoneId: row.zone_id,
      recordKey: row.record_key,
      recordName: row.record_name,
      recordType: row.record_type,
      changeAction: row.change_action,
      beforeValue: row.before_value,
      afterValue: row.after_value,
      source: row.source,
      changedByUserId: row.changed_by_user_id,
      changedByEmail: row.changed_by_email,
      changedAt: row.changed_at,
    }));

    return NextResponse.json({ items });
  } catch (err) {
    console.error('[ROUTE53-HISTORY] Failed to fetch record history:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Failed to fetch Route 53 record history' },
      { status: 500 }
    );
  }
}
