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 {
  listDocuments,
  createDocument,
  listInflightWorkflowsAggregatedByEntity,
} from '@/lib/services/documents.service';
import { listDocumentsSchema, createDocumentSchema } from '@/lib/validators/documents';

export const GET = withAuth(
  withPermission('documents', 'view', async (req, ctx) => {
    try {
      const query = parseQuery(req, listDocumentsSchema);

      if (query.entityType && query.entityId) {
        const result = await listInflightWorkflowsAggregatedByEntity(
          ctx.portId,
          query.entityType,
          query.entityId,
        );
        return NextResponse.json({ data: result });
      }

      const result = await listDocuments(ctx.portId, query, {
        // The caller's owned signing identities: their login email plus their
        // signing_email override (if set), so the "awaiting me" tab still
        // matches documents signed under a shared role mailbox.
        currentUserEmails: [ctx.user.email, ctx.user.signingEmail].filter((e): e is string => !!e),
      });

      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('documents', 'create', async (req, ctx) => {
    try {
      const body = await parseBody(req, createDocumentSchema);
      const doc = await createDocument(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: doc }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
