import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listThreads } from '@/lib/services/email-threads.service';
import { listThreadsSchema } from '@/lib/validators/email';

export const GET = withAuth(
  withPermission('email', 'view', async (req, ctx) => {
    try {
      const query = parseQuery(req, listThreadsSchema);
      const result = await listThreads(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);
    }
  }),
);
