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 } from '@/lib/errors';
import { listRecommendations, addManualRecommendation } from '@/lib/services/recommendations';

const addManualSchema = z.object({ berthId: z.string().min(1) });

// GET /api/v1/interests/[id]/recommendations
export const GET = withAuth(
  withPermission('interests', 'view', async (req, ctx, params) => {
    try {
      const recommendations = await listRecommendations(params.id!, ctx.portId);
      return NextResponse.json({ data: recommendations });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

// POST /api/v1/interests/[id]/recommendations - add manual recommendation
export const POST = withAuth(
  withPermission('interests', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, addManualSchema);
      const rec = await addManualRecommendation(params.id!, ctx.portId, body.berthId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: rec }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
