/**
 * GET /api/analyzer/itglue/writes
 *
 * Cross-asset write history — admin only. Powers /admin/itglue-writes.
 *
 * Query params: ?status=...&limit=...&offset=...
 */

import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/lib/auth-utils';
import {
  listAllWrites,
  type WriteStatus,
} from '@/lib/services/analyzer/asset-audit/persistence';

const ALLOWED_STATUSES: ReadonlyArray<WriteStatus> = [
  'pending',
  'committed',
  'failed',
  'reverted',
];

export async function GET(request: NextRequest) {
  const { error } = await requirePermission('admin', 'access');
  if (error) return error;

  const url = new URL(request.url);
  const limit = Number(url.searchParams.get('limit') ?? 100);
  const offset = Number(url.searchParams.get('offset') ?? 0);
  const statusParam = url.searchParams.get('status');
  const status = (
    statusParam && ALLOWED_STATUSES.includes(statusParam as WriteStatus)
      ? (statusParam as WriteStatus)
      : undefined
  );

  const writes = await listAllWrites({ limit, offset, status });
  return NextResponse.json({ writes });
}
