import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { mergeDuplicate } from '@/lib/services/expense-dedup.service';

const mergeSchema = z.object({
  /** Surviving expense id - typically the row's existing `duplicateOf` pointer. */
  targetId: z.string().min(1),
});

export const POST = withAuth(
  withPermission('expenses', 'edit', async (req, ctx, params) => {
    try {
      const sourceId = params.id;
      if (!sourceId) throw new ValidationError('id is required');
      const body = await parseBody(req, mergeSchema);
      await mergeDuplicate(sourceId, body.targetId, ctx.portId, ctx.userId);
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
