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

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

const listQuerySchema = z.object({
  entityType: z.string().optional(),
});

// Saved views are owner-only by design: every service call filters by
// (portId, userId), so any authenticated user can manage exactly their
// own views. We deliberately skip `withPermission(...)` here - there is
// no resource-level permission to add. See `savedViewsService` for the
// ownership filter that backs this route.
export const GET = withAuth(async (req, ctx) => {
  try {
    const { entityType } = parseQuery(req, listQuerySchema);
    const views = await savedViewsService.list(ctx.portId, ctx.userId, entityType);
    return NextResponse.json({ data: views });
  } catch (error) {
    return errorResponse(error);
  }
});

export const POST = withAuth(async (req, ctx) => {
  try {
    const body = await parseBody(req, createSavedViewSchema);
    const view = await savedViewsService.create(ctx.portId, ctx.userId, body);
    return NextResponse.json({ data: view }, { status: 201 });
  } catch (error) {
    return errorResponse(error);
  }
});
