import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { getInterestById, updateInterest, archiveInterest } from '@/lib/services/interests.service';
import { updateInterestSchema } from '@/lib/validators/interests';

export const GET = withAuth(
  withPermission('interests', 'view', async (req, ctx, params) => {
    try {
      const interest = await getInterestById(params.id!, ctx.portId);
      return NextResponse.json({ data: interest });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PATCH = withAuth(
  withPermission('interests', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, updateInterestSchema);
      const interest = await updateInterest(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: interest });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('interests', 'delete', async (req, ctx, params) => {
    try {
      await archiveInterest(params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
