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 { listInterests, createInterest } from '@/lib/services/interests.service';
import { listInterestsSchema, createInterestSchema } from '@/lib/validators/interests';

export const GET = withAuth(
  withPermission('interests', 'view', async (req, ctx) => {
    try {
      const query = parseQuery(req, listInterestsSchema);
      const result = await listInterests(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('interests', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createInterestSchema);
      const interest = await createInterest(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);
    }
  }),
);
