import { NextResponse } from 'next/server';
import { and, desc, eq } from 'drizzle-orm';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { interestFieldHistory } from '@/lib/db/schema';
import { errorResponse } from '@/lib/errors';

/**
 * GET /api/v1/clients/[id]/field-history
 *
 * Returns every supplemental-form override that touched the client (rolling
 * up across all of their interests), newest first. Powers the inline clock
 * icon + popover on Client detail. Mirrors /interests/[id]/field-history.
 */
export const GET = withAuth(
  withPermission('clients', 'view', async (_req, ctx, params) => {
    try {
      const rows = await db
        .select()
        .from(interestFieldHistory)
        .where(
          and(
            eq(interestFieldHistory.portId, ctx.portId),
            eq(interestFieldHistory.clientId, params.id!),
          ),
        )
        .orderBy(desc(interestFieldHistory.createdAt))
        .limit(100);
      return NextResponse.json({ data: rows });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
