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 {
  createResidentialClient,
  listResidentialClients,
} from '@/lib/services/residential.service';
import {
  createResidentialClientSchema,
  listResidentialClientsSchema,
} from '@/lib/validators/residential';

export const GET = withAuth(
  withPermission('residential_clients', 'view', async (req, ctx) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const query = parseQuery(req, listResidentialClientsSchema);
      const result = await listResidentialClients(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_clients', 'create', async (req, ctx) => {
    try {
      await assertResidentialModuleEnabled(ctx.portId);
      const body = await parseBody(req, createResidentialClientSchema);
      const client = await createResidentialClient(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: client }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
