import 'server-only';

import {
  downloadArtifact,
} from '@/features/foundation/document-artifact/server/service';
import {
  downloadActiveDocumentLibraryVersion,
  downloadDocumentLibraryVersion,
} from '@/features/foundation/document-library/server/service';
import type {
  NotificationAttachmentRef,
  ResolvedNotificationAttachment,
} from '../types';

async function streamToBuffer(stream: ReadableStream<Uint8Array>) {
  return Buffer.from(await new Response(stream).arrayBuffer());
}

export async function resolveNotificationAttachments(input: {
  organizationId: string;
  userId: string;
  attachments: NotificationAttachmentRef[];
}): Promise<ResolvedNotificationAttachment[]> {
  return Promise.all(
    input.attachments.map(async (attachment) => {
      if (attachment.type === 'artifact') {
        const result = await downloadArtifact({
          artifactId: attachment.artifactId,
          organizationId: input.organizationId,
          userId: input.userId,
          auditDownload: false,
        });

        return {
          sourceType: 'artifact' as const,
          sourceId: attachment.artifactId,
          fileName: result.object.fileName ?? result.artifact.fileName,
          contentType: result.object.contentType,
          size: result.object.size,
          checksum: result.object.checksum ?? null,
          label: attachment.label ?? null,
          buffer: await streamToBuffer(result.object.body),
        };
      }

      if (attachment.type === 'document_library_version') {
        const result = await downloadDocumentLibraryVersion({
          versionId: attachment.versionId,
          organizationId: input.organizationId,
          userId: input.userId,
        });

        return {
          sourceType: 'document_library_version' as const,
          sourceId: attachment.versionId,
          fileName: result.object.fileName,
          contentType: result.object.contentType,
          size: result.object.size,
          checksum: result.object.checksum ?? null,
          label: attachment.label ?? null,
          buffer: await streamToBuffer(result.object.body),
        };
      }

      const result = await downloadActiveDocumentLibraryVersion({
        libraryId: attachment.libraryId,
        organizationId: input.organizationId,
        userId: input.userId,
      });

      return {
        sourceType: 'active_document_library' as const,
        sourceId: attachment.libraryId,
        fileName: result.object.fileName,
        contentType: result.object.contentType,
        size: result.object.size,
        checksum: result.object.checksum ?? null,
        label: attachment.label ?? null,
        buffer: await streamToBuffer(result.object.body),
      };
    }),
  );
}
