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/interests/[id]/field-history
 *
 * Returns the field-level override log for the interest, newest first.
 * Powers the "Field history" panel on Interest detail (and the matching
 * panel on Client detail via /clients/[id]/field-history).
 */
export const GET = withAuth(
  withPermission('interests', 'view', async (_req, ctx, params) => {
    try {
      const rows = await db
        .select()
        .from(interestFieldHistory)
        .where(
          and(
            eq(interestFieldHistory.portId, ctx.portId),
            eq(interestFieldHistory.interestId, params.id!),
          ),
        )
        .orderBy(desc(interestFieldHistory.createdAt))
        .limit(100);
      return NextResponse.json({ data: rows });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
