import { getEnvelopeById } from '@documenso/lib/server-only/envelope/get-envelope-by-id';

import { findAttachmentsByEnvelopeId } from '@documenso/lib/server-only/envelope-attachment/find-attachments-by-envelope-id';
import { EnvelopeType } from '@prisma/client';

import { authenticatedProcedure } from '../../trpc';
import { ZFindAttachmentsRequestSchema, ZFindAttachmentsResponseSchema } from './find-attachments.types';

export const findAttachmentsRoute = authenticatedProcedure
  .meta({
    openapi: {
      method: 'GET',
      path: '/document/attachment',
      summary: 'Find attachments',
      description:
        'Deprecated: this endpoint is being replaced by the Envelope API. See https://docs.documenso.com/docs/developers/api/migrate-to-envelopes for the migration guide. Find all attachments for a document',
      tags: ['Document'],
      deprecated: true,
    },
  })
  .input(ZFindAttachmentsRequestSchema)
  .output(ZFindAttachmentsResponseSchema)
  .query(async ({ input, ctx }) => {
    const { documentId } = input;
    const { teamId } = ctx;
    const userId = ctx.user.id;

    ctx.logger.info({
      input: { documentId },
    });

    const envelope = await getEnvelopeById({
      id: {
        type: 'documentId',
        id: documentId,
      },
      userId,
      teamId,
      type: EnvelopeType.DOCUMENT,
    });

    const data = await findAttachmentsByEnvelopeId({
      envelopeId: envelope.id,
      teamId,
      userId,
    });

    return {
      data,
    };
  });
