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 {
  archiveResidentialClient,
  getResidentialClientById,
  updateResidentialClient,
} from '@/lib/services/residential.service';
import { updateResidentialClientSchema } from '@/lib/validators/residential';

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

export const PATCH = withAuth(
  withPermission('residential_clients', 'edit', async (req, ctx, params) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const body = await parseBody(req, updateResidentialClientSchema);
      const updated = await updateResidentialClient(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_clients', 'delete', async (req, ctx, params) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      await archiveResidentialClient(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);
    }
  }),
);
