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 { assertResidentialModuleEnabled } from '@/lib/services/residential-module.service';
import {
  archiveResidentialInterest,
  getResidentialInterestById,
  updateResidentialInterest,
} from '@/lib/services/residential.service';
import { updateResidentialInterestSchema } from '@/lib/validators/residential';

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

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

export const DELETE = withAuth(
  withPermission('residential_interests', 'delete', async (req, ctx, params) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      await archiveResidentialInterest(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);
    }
  }),
);
