import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery, parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { assertResidentialModuleEnabled } from '@/lib/services/residential-module.service';
import {
  createResidentialInterest,
  listResidentialInterests,
} from '@/lib/services/residential.service';
import {
  createResidentialInterestSchema,
  listResidentialInterestsSchema,
} from '@/lib/validators/residential';

export const GET = withAuth(
  withPermission('residential_interests', 'view', async (req, ctx) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const query = parseQuery(req, listResidentialInterestsSchema);
      const result = await listResidentialInterests(ctx.portId, query);
      const { page, limit } = query;
      const totalPages = Math.ceil(result.total / limit);
      return NextResponse.json({
        data: result.data,
        pagination: {
          page,
          pageSize: limit,
          total: result.total,
          totalPages,
          hasNextPage: page < totalPages,
          hasPreviousPage: page > 1,
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('residential_interests', 'create', async (req, ctx) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const body = await parseBody(req, createResidentialInterestSchema);
      const interest = await createResidentialInterest(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: interest }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
