import { NextResponse } from 'next/server';

import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { savedViewsService } from '@/lib/services/saved-views.service';
import { updateSavedViewSchema } from '@/lib/validators/saved-views';

export const PATCH = withAuth(async (req, ctx, params) => {
  try {
    const id = params.id ?? '';
    const body = await parseBody(req, updateSavedViewSchema);
    const view = await savedViewsService.update(ctx.portId, ctx.userId, id, body);
    return NextResponse.json({ data: view });
  } catch (error) {
    return errorResponse(error);
  }
});

export const DELETE = withAuth(async (_req, ctx, params) => {
  try {
    const id = params.id ?? '';
    await savedViewsService.delete(ctx.portId, ctx.userId, id);
    return NextResponse.json({ data: null }, { status: 200 });
  } catch (error) {
    return errorResponse(error);
  }
});
