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 { listClients, createClient } from '@/lib/services/clients.service';
import { listClientsSchema, createClientSchema } from '@/lib/validators/clients';

export const GET = withAuth(
  withPermission('clients', 'view', async (req, ctx) => {
    try {
      const query = parseQuery(req, listClientsSchema);
      const result = await listClients(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('clients', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createClientSchema);
      const client = await createClient(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);
    }
  }),
);
