Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

46.8 KB
Raw Blame
import type { ApiKey } from '../api-keys/api-keys.types';
import type { CustomPropertyDefinition } from '../custom-properties/custom-properties.types';
import type { Document } from '../documents/documents.types';
import type { Webhook } from '../webhooks/webhooks.types';
import type { DocumentCustomPropertyValueStorage, DocumentFile } from './demo.storage';
import { FetchError } from 'ofetch';
import { createRouter } from 'radix3';
import { get } from '../shared/utils/get';
import { defineHandler } from './demo-api-mock.models';
import { createId, randomString } from './demo.models';
import {
  apiKeyStorage,
  customPropertyDefinitionStorage,
  documentCustomPropertyValueStorage,
  documentFileStorage,
  documentStorage,
  documentViewStorage,
  organizationStorage,
  tagDocumentStorage,
  taggingRuleStorage,
  tagStorage,
  webhooksStorage,
} from './demo.storage';
import { findMany, getValues } from './demo.storage.models';
import { generatePropertyKey, searchDemoDocuments } from './search/demo.search.services';
import { demoUser } from './seed/users.fixtures';
import { stringify } from '@papra/std';

function assert(
  condition: unknown,
  { message = 'Error', status }: { message?: string; status?: number } = {},
): asserts condition {
  if (!condition) {
    throw Object.assign(new FetchError(message), { status });
  }
}

async function toBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = reject;
  });
}

async function fromBase64(base64: string) {
  return fetch(base64).then(async (res) => res.blob());
}

async function serializeFile(file: File): Promise<DocumentFile> {
  return {
    name: file.name,
    size: file.size,
    type: file.type,
    // base64
    base64Content: await toBase64(file),
  };
}

async function deserializeFile(storageInfo: DocumentFile): Promise<File> {
  if ('path' in storageInfo) {
    const { path, name } = storageInfo;
    const response = await fetch(path);
    const blob = await response.blob();
    return new File([blob], name);
  }

  const { name, type, base64Content } = storageInfo;

  return new File([await fromBase64(base64Content)], name, { type });
}

function hydratePropertyValue({
  value,
  definition,
}: {
  value: unknown;
  definition: CustomPropertyDefinition;
}): unknown {
  if (value == null) {
    return null;
  }

  if (definition.type === 'select') {
    const optionId = stringify(value);
    const option = definition.options.find((o) => o.id === optionId || o.key === optionId);

    if (!option) {
      return null;
    }

    return { optionId: option.id, name: option.name };
  }

  if (definition.type === 'multi_select') {
    const ids = Array.isArray(value) ? value.map(String) : [stringify(value)];

    return ids
      .map((id) => {
        const option = definition.options.find((o) => o.id === id || o.key === id);

        return option ? { optionId: option.id, name: option.name } : null;
      })
      .filter((v) => v !== null);
  }

  return value;
}

function buildCustomPropertiesResponse({
  definitions,
  storedValues,
  documentId,
}: {
  definitions: CustomPropertyDefinition[];
  storedValues: DocumentCustomPropertyValueStorage[];
  documentId: string;
}) {
  const documentValues = storedValues.filter((v) => v.documentId === documentId);
  const valuesByDefinitionId = Object.fromEntries(
    documentValues.map((v) => [v.propertyDefinitionId, v.value]),
  );

  return definitions
    .toSorted((a, b) => a.displayOrder - b.displayOrder)
    .map((def) => ({
      propertyDefinitionId: def.id,
      key: def.key,
      name: def.name,
      type: def.type,
      displayOrder: def.displayOrder,
      value: hydratePropertyValue({ value: valuesByDefinitionId[def.id] ?? null, definition: def }),
    }));
}

async function resolveBatchTargetDocumentIds({
  filter,
  organizationId,
}: {
  filter: { documentIds: string[] } | { query: string };
  organizationId: string;
}): Promise<string[]> {
  if ('documentIds' in filter) {
    const documents = await Promise.all(
      filter.documentIds.map(async (id) => documentStorage.getItem(`${organizationId}:${id}`)),
    );

    assert(
      documents.every((doc) => doc?.organizationId === organizationId),
      { status: 403 },
    );

    return filter.documentIds;
  }

  const [organizationDocuments, allTags, tagDocuments, allDefinitions, allPropertyValues] =
    await Promise.all([
      findMany(
        documentStorage,
        (document) => document?.organizationId === organizationId && !document?.deletedAt,
      ),
      getValues(tagStorage),
      getValues(tagDocumentStorage),
      findMany(customPropertyDefinitionStorage, (def) => def.organizationId === organizationId),
      getValues(documentCustomPropertyValueStorage),
    ]);

  const documentsWithTagsAndProperties = organizationDocuments.map((document) => {
    const documentTagDocuments = tagDocuments.filter(
      (tagDocument) => tagDocument?.documentId === document?.id,
    );
    const tags = allTags.filter((tag) =>
      documentTagDocuments.some((tagDocument) => tagDocument?.tagId === tag?.id),
    );

    const customProperties = buildCustomPropertiesResponse({
      definitions: allDefinitions,
      storedValues: allPropertyValues,
      documentId: document.id,
    });

    return { ...document, tags, customProperties };
  });

  return searchDemoDocuments({
    query: filter.query,
    documents: documentsWithTagsAndProperties as unknown as Document[],
  }).map((document) => document.id);
}

const inMemoryApiMock: Record<string, { handler: any }> = {
  ...defineHandler({
    path: '/api/config',
    method: 'GET',
    handler: () => ({
      config: {
        auth: {
          isEmailVerificationRequired: false,
          isPasswordResetEnabled: false,
          providers: {
            github: { isEnabled: false },
          },
        },
      },
    }),
  }),

  ...defineHandler({
    path: '/api/users/me',
    method: 'GET',
    handler: () => ({
      user: demoUser,
    }),
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      // body is a FormData instance with file field

      const file = (body as FormData).get('file') as File;

      assert(file, { status: 400 });

      const document = {
        id: createId({ prefix: 'doc' }),
        organizationId,
        name: file.name,
        originalName: file.name,
        originalSize: file.size,
        mimeType: file.type,
        content: '',
        createdAt: new Date(),
        updatedAt: new Date(),
        tags: [],
      };

      const key = `${organizationId}:${document.id}`;

      await documentFileStorage.setItem(key, await serializeFile(file));
      await documentStorage.setItem(key, document);

      // Simulate a slow response
      await new Promise((resolve) => setTimeout(resolve, 500));

      return { document };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/customer-portal',
    method: 'GET',
    handler: async () => {
      throw Object.assign(new FetchError('Not available in demo'), { status: 501 });
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/statistics',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const documents = await findMany(
        documentStorage,
        (document) => document.organizationId === organizationId,
      );

      return {
        organizationStats: {
          documentsCount: documents.length,
          documentsSize: documents.reduce((acc, document) => acc + document.originalSize, 0),
        },
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents',
    method: 'GET',
    handler: async ({ params: { organizationId }, query }) => {
      const {
        pageIndex = 0,
        pageSize = 5,
        searchQuery: rawSearchQuery = '',
        sortField = 'createdAt',
        sortOrder = 'desc',
      } = query ?? {};

      const organization = await organizationStorage.getItem(organizationId);
      assert(organization, { status: 403 });

      const searchQuery = rawSearchQuery.trim();
      const [organizationDocuments, allTags, tagDocuments, allDefinitions, allPropertyValues] =
        await Promise.all([
          findMany(
            documentStorage,
            (document) => document?.organizationId === organizationId && !document?.deletedAt,
          ),
          getValues(tagStorage),
          getValues(tagDocumentStorage),
          findMany(customPropertyDefinitionStorage, (def) => def.organizationId === organizationId),
          getValues(documentCustomPropertyValueStorage),
        ]);

      const documentsWithTagsAndProperties = organizationDocuments.map((document) => {
        const documentTagDocuments = tagDocuments.filter(
          (tagDocument) => tagDocument?.documentId === document?.id,
        );
        const tags = allTags.filter((tag) =>
          documentTagDocuments.some((tagDocument) => tagDocument?.tagId === tag?.id),
        );

        const customProperties = buildCustomPropertiesResponse({
          definitions: allDefinitions,
          storedValues: allPropertyValues,
          documentId: document.id,
        });

        return {
          ...document,
          tags,
          customProperties,
        };
      });

      const filteredDocuments = searchDemoDocuments({
        query: searchQuery,
        documents: documentsWithTagsAndProperties as unknown as Document[],
      });

      const getSortValue = (document: Document) => {
        if (sortField === 'name') {
          return document.name?.toLowerCase() ?? '';
        }
        if (sortField === 'documentDate') {
          return document.documentDate ? new Date(document.documentDate).getTime() : 0;
        }
        if (sortField === 'updatedAt') {
          return document.updatedAt ? new Date(document.updatedAt).getTime() : 0;
        }
        return document.createdAt ? new Date(document.createdAt).getTime() : 0;
      };

      const sortDirection = sortOrder === 'asc' ? 1 : -1;
      const paginatedDocuments = filteredDocuments
        .toSorted((a, b) => {
          const av = getSortValue(a);
          const bv = getSortValue(b);
          if (av < bv) {
            return -1 * sortDirection;
          }
          if (av > bv) {
            return 1 * sortDirection;
          }
          return 0;
        })
        .slice(pageIndex * pageSize, (pageIndex + 1) * pageSize);

      return {
        documents: paginatedDocuments,
        documentsCount: filteredDocuments.length,
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/deleted',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);
      assert(organization, { status: 403 });

      const deletedDocuments = await findMany(
        documentStorage,
        (document) =>
          document.organizationId === organizationId && document.deletedAt !== undefined,
      );

      return {
        documents: deletedDocuments,
        documentsCount: deletedDocuments.length,
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId',
    method: 'GET',
    handler: async ({ params: { organizationId, documentId } }) => {
      const key = `${organizationId}:${documentId}`;
      const document = await documentStorage.getItem(key);

      assert(document, { status: 404 });

      const [tagDocuments, allDefinitions, allPropertyValues] = await Promise.all([
        findMany(tagDocumentStorage, (tagDocument) => tagDocument.documentId === documentId),
        findMany(customPropertyDefinitionStorage, (def) => def.organizationId === organizationId),
        findMany(documentCustomPropertyValueStorage, (v) => v.documentId === documentId),
      ]);

      const tags = await findMany(tagStorage, (tag) =>
        tagDocuments.some((tagDocument) => tagDocument.tagId === tag.id),
      );

      const customProperties = buildCustomPropertiesResponse({
        definitions: allDefinitions,
        storedValues: allPropertyValues,
        documentId,
      });

      return {
        document: {
          ...document,
          tags,
          customProperties,
        },
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/restore',
    method: 'POST',
    handler: async ({ params: { organizationId, documentId } }) => {
      const key = `${organizationId}:${documentId}`;
      const document = await documentStorage.getItem(key);

      assert(document, { status: 404 });

      document.deletedAt = undefined;
      document.deletedBy = undefined;
      document.updatedAt = new Date();

      await documentStorage.setItem(key, document);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId',
    method: 'DELETE',
    handler: async ({ params: { organizationId, documentId } }) => {
      const key = `${organizationId}:${documentId}`;

      const document = await documentStorage.getItem(key);
      assert(document, { status: 404 });

      const now = new Date();

      document.deletedAt = now;
      document.updatedAt = now;
      document.deletedBy = 'usr_1';

      await documentStorage.setItem(key, document);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/file',
    method: 'GET',
    handler: async ({ params }) => {
      const { organizationId, documentId } = params;
      const key = `${organizationId}:${documentId}`;

      const file = await documentFileStorage.getItem(key);

      assert(file, { status: 404 });

      return deserializeFile(file);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tags',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const tags = await findMany(tagStorage, (tag) => tag.organizationId === organizationId);
      const tagDocuments = await getValues(tagDocumentStorage);

      const tagsWithDocumentsCount = tags.map((tag) => ({
        ...tag,
        documentsCount: tagDocuments.filter((tagDocument) => tagDocument.tagId === tag.id).length,
      }));

      return {
        tags: tagsWithDocumentsCount,
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tags',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const name = get(body, ['name']) as string;
      const existingTagsWithSameName = await findMany(
        tagStorage,
        (tag) =>
          tag.organizationId === organizationId && tag.name.toLowerCase() === name.toLowerCase(),
      );

      if (existingTagsWithSameName.length > 0) {
        throw Object.assign(new FetchError('Tag already exists'), {
          status: 400,
          data: { error: { code: 'tags.already_exists' } },
        });
      }

      const tag = {
        id: createId({ prefix: 'tag' }),
        organizationId,
        name,
        color: get(body, ['color']) as string,
        description: (get(body, ['description']) ?? null) as string | null,
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      await tagStorage.setItem(tag.id, tag);

      return { tag };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tags/:tagId',
    method: 'PUT',
    handler: async ({ params: { organizationId, tagId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const tag = await tagStorage.getItem(tagId);

      assert(tag, { status: 404 });

      const newName = get(body, ['name']) as string | undefined;
      if (newName) {
        const existingTagsWithSameName = await findMany(
          tagStorage,
          (t) =>
            t.organizationId === organizationId &&
            t.id !== tagId &&
            t.name.toLowerCase() === newName.toLowerCase(),
        );

        if (existingTagsWithSameName.length > 0) {
          throw Object.assign(new FetchError('Tag already exists'), {
            status: 400,
            data: { error: { code: 'tags.already_exists' } },
          });
        }
      }

      await tagStorage.setItem(tagId, Object.assign(tag, body, { updatedAt: new Date() }));

      return { tag };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tags/:tagId',
    method: 'DELETE',
    handler: async ({ params: { organizationId, tagId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      await tagStorage.removeItem(tagId);

      const tagDocuments = await findMany(
        tagDocumentStorage,
        (tagDocument) => tagDocument.tagId === tagId,
      );

      await Promise.all(
        tagDocuments.map(async (tagDocument) => tagDocumentStorage.removeItem(tagDocument.id)),
      );
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/tags',
    method: 'POST',
    handler: async ({ params: { organizationId, documentId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const tagId = get(body, ['tagId']) as string;

      assert(tagId, { status: 400 });

      const tagDocument = {
        id: createId({ prefix: 'tagDoc' }),
        tagId,
        documentId,
        createdAt: new Date(),
      };

      await tagDocumentStorage.setItem(tagDocument.id, tagDocument);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/tags/:tagId',
    method: 'DELETE',
    handler: async ({ params: { organizationId, documentId, tagId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const tagDocuments = await findMany(
        tagDocumentStorage,
        (tagDocument) => tagDocument.tagId === tagId && tagDocument.documentId === documentId,
      );

      await Promise.all(
        tagDocuments.map(async (tagDocument) => tagDocumentStorage.removeItem(tagDocument.id)),
      );
    },
  }),

  ...defineHandler({
    path: '/api/organizations',
    method: 'GET',
    handler: async () => {
      const organizations = await getValues(organizationStorage);

      return { organizations };
    },
  }),

  ...defineHandler({
    path: '/api/organizations',
    method: 'POST',
    handler: async ({ body }) => {
      const organization = {
        id: createId({ prefix: 'org' }),
        name: get(body, ['name']) as string,
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      await organizationStorage.setItem(organization.id, organization);

      return { organization };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      return { organization };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId',
    method: 'DELETE',
    handler: async ({ params: { organizationId } }) => {
      await organizationStorage.removeItem(organizationId);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId',
    method: 'PUT',
    handler: async ({ params: { organizationId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      organization.name = get(body, ['name']) as string;
      organization.updatedAt = new Date();

      await organizationStorage.setItem(organizationId, organization);

      return { organization };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tagging-rules',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const taggingRules = await findMany(
        taggingRuleStorage,
        (taggingRule) => taggingRule.organizationId === organizationId,
      );

      return { taggingRules };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tagging-rules',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      const taggingRule = {
        id: createId({ prefix: 'tr' }),
        organizationId,
        name: get(body, ['name']) as string,
        description: (get(body, ['description']) ?? '') as string,
        conditions: get(body, ['conditions']) as any,
        actions: (get(body, ['tagIds']) as string[]).map((tagId: string) => ({ tagId })),
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      await taggingRuleStorage.setItem(taggingRule.id, taggingRule);

      return { taggingRule };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
    method: 'GET',
    handler: async ({ params: { taggingRuleId } }) => {
      const taggingRule = await taggingRuleStorage.getItem(taggingRuleId);

      assert(taggingRule, { status: 404 });

      return { taggingRule };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
    method: 'DELETE',
    handler: async ({ params: { taggingRuleId } }) => {
      await taggingRuleStorage.removeItem(taggingRuleId);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
    method: 'PUT',
    handler: async ({ params: { taggingRuleId }, body }) => {
      const taggingRule = await taggingRuleStorage.getItem(taggingRuleId);

      assert(taggingRule, { status: 404 });

      await taggingRuleStorage.setItem(
        taggingRuleId,
        Object.assign(taggingRule, body, { updatedAt: new Date() }),
      );

      return { taggingRule };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/batch/trash',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);
      assert(organization, { status: 403 });

      const filter = get(body, ['filter']) as { documentIds: string[] } | { query: string };
      assert(filter, { status: 400 });

      const documentIds = await resolveBatchTargetDocumentIds({ filter, organizationId });

      const now = new Date();
      const trashedDocumentIds: string[] = [];

      await Promise.all(
        documentIds.map(async (documentId) => {
          const key = `${organizationId}:${documentId}`;
          const document = await documentStorage.getItem(key);

          if (!document || document.deletedAt) {
            return;
          }

          document.deletedAt = now;
          document.updatedAt = now;
          document.deletedBy = 'usr_1';

          await documentStorage.setItem(key, document);
          trashedDocumentIds.push(documentId);
        }),
      );

      return { trashedDocumentIds, trashedCount: trashedDocumentIds.length };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/batch/tags',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);
      assert(organization, { status: 403 });

      const filter = get(body, ['filter']) as { documentIds: string[] } | { query: string };
      const addTagIds = (get(body, ['addTagIds']) ?? []) as string[];
      const removeTagIds = (get(body, ['removeTagIds']) ?? []) as string[];

      assert(filter, { status: 400 });
      assert(addTagIds.length + removeTagIds.length > 0, { status: 400 });

      const requestedTagIds = [...new Set([...addTagIds, ...removeTagIds])];
      const requestedTags = await Promise.all(
        requestedTagIds.map(async (id) => tagStorage.getItem(id)),
      );

      assert(
        requestedTags.every((tag) => tag?.organizationId === organizationId),
        { status: 404, message: 'Tag not found' },
      );

      const documentIds = await resolveBatchTargetDocumentIds({ filter, organizationId });

      if (documentIds.length === 0) {
        return { taggedCount: 0, untaggedCount: 0, insertedPairs: [], removedPairs: [] };
      }

      const existingTagDocuments = await getValues(tagDocumentStorage);
      const insertedPairs: { documentId: string; tagId: string }[] = [];
      const removedPairs: { documentId: string; tagId: string }[] = [];

      for (const documentId of documentIds) {
        for (const tagId of addTagIds) {
          const alreadyExists = existingTagDocuments.some(
            (td) => td.documentId === documentId && td.tagId === tagId,
          );
          if (alreadyExists) {
            continue;
          }

          const tagDocument = {
            id: createId({ prefix: 'tagDoc' }),
            tagId,
            documentId,
            createdAt: new Date(),
          };

          await tagDocumentStorage.setItem(tagDocument.id, tagDocument);
          insertedPairs.push({ documentId, tagId });
        }

        for (const tagId of removeTagIds) {
          const toRemove = existingTagDocuments.filter(
            (td) => td.documentId === documentId && td.tagId === tagId,
          );

          await Promise.all(toRemove.map(async (td) => tagDocumentStorage.removeItem(td.id)));

          if (toRemove.length > 0) {
            removedPairs.push({ documentId, tagId });
          }
        }
      }

      return {
        taggedCount: insertedPairs.length,
        untaggedCount: removedPairs.length,
        insertedPairs,
        removedPairs,
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/trash',
    method: 'DELETE',
    handler: async ({ params: { organizationId } }) => {
      const documents = await findMany(
        documentStorage,
        (document) => document.organizationId === organizationId && Boolean(document.deletedAt),
      );

      await Promise.all(
        documents.map(async (document) =>
          documentStorage.removeItem(`${organizationId}:${document.id}`),
        ),
      );
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/trash/:documentId',
    method: 'DELETE',
    handler: async ({ params: { organizationId, documentId } }) => {
      const key = `${organizationId}:${documentId}`;

      await documentStorage.removeItem(key);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/members',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      return {
        members: [
          {
            id: 'mem_1',
            user: demoUser,
            role: 'owner',
            organizationId,
          },
        ],
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/members/invitations',
    method: 'POST',
    handler: async () => {
      throw Object.assign(new FetchError('Not available in demo'), {
        status: 501,
        data: {
          error: {
            message: 'This feature is not available in demo',
            code: 'demo.not_available',
          },
        },
      });
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/members/me',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      return {
        member: {
          id: 'mem_1',
          role: 'owner',
          organizationId,
        },
      };
    },
  }),

  ...defineHandler({
    path: '/api/api-keys',
    method: 'GET',
    handler: async () => {
      const apiKeys = await getValues(apiKeyStorage);

      return { apiKeys };
    },
  }),

  ...defineHandler({
    path: '/api/api-keys',
    method: 'POST',
    handler: async ({ body }) => {
      const token = `ppapi_${randomString({ length: 64 })}`;

      const apiKey = {
        id: createId({ prefix: 'apiKey' }),
        name: get(body, ['name']),
        permissions: get(body, ['permissions']),
        organizationIds: get(body, ['organizationIds']),
        allOrganizations: get(body, ['allOrganizations']),
        expiresAt: get(body, ['expiresAt']),
        createdAt: new Date(),
        updatedAt: new Date(),
        prefix: token.slice(0, 11),
      } as ApiKey;

      await apiKeyStorage.setItem(apiKey.id, apiKey);

      return { apiKey, token };
    },
  }),

  ...defineHandler({
    path: '/api/api-keys/:apiKeyId',
    method: 'DELETE',
    handler: async ({ params: { apiKeyId } }) => {
      await apiKeyStorage.removeItem(apiKeyId);
    },
  }),

  ...defineHandler({
    path: '/api/invitations/count',
    method: 'GET',
    handler: async () => ({ pendingInvitationsCount: 0 }),
  }),

  ...defineHandler({
    path: '/api/invitations',
    method: 'GET',
    handler: async () => ({ invitations: [] }),
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/webhooks',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const webhooks = await findMany(
        webhooksStorage,
        (webhook) => webhook.organizationId === organizationId,
      );

      return { webhooks };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/webhooks',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      const webhook: Webhook = {
        id: createId({ prefix: 'webhook' }),
        organizationId,
        name: get(body, ['name']) as string,
        url: get(body, ['url']) as string,
        enabled: true,
        events: get(body, ['events']) as Webhook['events'],
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      await webhooksStorage.setItem(webhook.id, webhook);

      return { webhook };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/webhooks/:webhookId',
    method: 'GET',
    handler: async ({ params: { webhookId } }) => {
      const webhook = await webhooksStorage.getItem(webhookId);
      return { webhook };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/webhooks/:webhookId',
    method: 'DELETE',
    handler: async ({ params: { webhookId } }) => {
      await webhooksStorage.removeItem(webhookId);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/webhooks/:webhookId',
    method: 'PUT',
    handler: async ({ params: { webhookId }, body }) => {
      const webhook = await webhooksStorage.getItem(webhookId);

      assert(webhook, { status: 404 });

      await webhooksStorage.setItem(
        webhookId,
        Object.assign(webhook, body, { updatedAt: new Date() }),
      );

      return { webhook };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId',
    method: 'PATCH',
    handler: async ({ params: { organizationId, documentId }, body }) => {
      const document = await documentStorage.getItem(`${organizationId}:${documentId}`);

      assert(document, { status: 404 });

      const { name, content, documentDate, notes } = body as {
        name?: string;
        content?: string;
        documentDate?: string;
        notes?: string;
      };

      const newDocument = {
        ...document,
        ...(name !== undefined && { name }),
        ...(content !== undefined && { content }),
        ...(documentDate !== undefined && {
          documentDate: documentDate === null ? null : new Date(documentDate),
        }),
        ...(notes !== undefined && { notes }),
        updatedAt: new Date(),
      };

      await documentStorage.setItem(`${organizationId}:${documentId}`, newDocument as Document); // TODO: introduce a storage/serialized type

      return { document: newDocument };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/activity',
    method: 'GET',
    handler: async ({ params: { organizationId, documentId }, query }) => {
      const key = `${organizationId}:${documentId}`;
      const document = await documentStorage.getItem(key);

      assert(document, { status: 404 });

      const { pageIndex = 0 } = query ?? {};

      // Return mock activity for demo - just a created event
      const activities =
        pageIndex === 0
          ? [
              {
                id: 'activity_1',
                documentId,
                event: 'created',
                eventData: {},
                createdAt: document.createdAt,
                user: {
                  id: 'usr_1',
                  name: 'Sherlock Holmes',
                },
              },
            ]
          : [];

      return { activities };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/subscription',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      // Demo mode uses free plan with no subscription
      return {
        subscription: null,
        plan: {
          id: 'free',
          name: 'Free',
          limits: {
            maxDocumentStorageBytes: 1024 * 1024 * 500, // 500 MiB
            maxIntakeEmailsCount: 1,
            maxOrganizationsMembersCount: 3,
            maxFileSize: 1024 * 1024 * 50, // 50 MiB
            aiCreditsPerMonth: 1000,
          },
        },
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/usage',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const documents = await findMany(
        documentStorage,
        (document) => document.organizationId === organizationId,
      );

      const totalDocumentsSize = documents.reduce((acc, doc) => acc + (doc.originalSize ?? 0), 0);
      const deletedDocumentsSize = documents
        .filter((doc) => doc.deletedAt)
        .reduce((acc, doc) => acc + (doc.originalSize ?? 0), 0);

      return {
        usage: {
          documentsStorage: {
            used: totalDocumentsSize,
            deleted: deletedDocumentsSize,
            limit: 1024 * 1024 * 500, // 500 MiB
          },
          intakeEmailsCount: {
            used: 0,
            limit: 1,
          },
          membersCount: {
            used: 1,
            limit: 3,
          },
          aiCredits: {
            used: 0,
            limit: 1000,
          },
        },
        limits: {
          maxDocumentStorageBytes: 1024 * 1024 * 500, // 500 MiB
          maxIntakeEmailsCount: 1,
          maxOrganizationsMembersCount: 3,
          maxFileSize: 1024 * 1024 * 50, // 50 MiB
          aiCreditsPerMonth: 1000,
        },
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/custom-properties',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const propertyDefinitions = await findMany(
        customPropertyDefinitionStorage,
        (def) => def.organizationId === organizationId,
      );

      return { propertyDefinitions };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/custom-properties',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const existingDefinitions = await findMany(
        customPropertyDefinitionStorage,
        (def) => def.organizationId === organizationId,
      );

      const propertyDefinition = {
        id: createId({ prefix: 'cpd' }),
        organizationId,
        name: get(body, ['name']) as string,
        key: generatePropertyKey({ name: get(body, ['name']) as string }),
        description: (get(body, ['description']) ?? null) as string | null,
        type: get(body, ['type']) as string,
        displayOrder: existingDefinitions.length,
        options: ((get(body, ['options']) as { name: string }[]) ?? []).map((option, index) => ({
          id: createId({ prefix: 'opt' }),
          name: option.name,
          key: generatePropertyKey({ name: option.name }),
          displayOrder: index,
        })),
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      await customPropertyDefinitionStorage.setItem(
        propertyDefinition.id,
        propertyDefinition as any,
      );

      return { propertyDefinition };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/custom-properties/:propertyDefinitionId',
    method: 'GET',
    handler: async ({ params: { organizationId, propertyDefinitionId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const definition = await customPropertyDefinitionStorage.getItem(propertyDefinitionId);

      assert(definition, { status: 404 });

      return { definition };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/custom-properties/:propertyDefinitionId',
    method: 'PUT',
    handler: async ({ params: { organizationId, propertyDefinitionId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const propertyDefinition =
        await customPropertyDefinitionStorage.getItem(propertyDefinitionId);

      assert(propertyDefinition, { status: 404 });

      const updatedDefinition = Object.assign(propertyDefinition, body, { updatedAt: new Date() });

      await customPropertyDefinitionStorage.setItem(propertyDefinitionId, updatedDefinition);

      return { propertyDefinition: updatedDefinition };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/custom-properties/:propertyDefinitionId',
    method: 'DELETE',
    handler: async ({ params: { organizationId, propertyDefinitionId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      await customPropertyDefinitionStorage.removeItem(propertyDefinitionId);

      // Remove all values associated with this definition
      const values = await findMany(
        documentCustomPropertyValueStorage,
        (v) => v.propertyDefinitionId === propertyDefinitionId,
      );

      await Promise.all(
        values.map(async (v) =>
          documentCustomPropertyValueStorage.removeItem(`${v.documentId}:${propertyDefinitionId}`),
        ),
      );
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/custom-properties',
    method: 'GET',
    handler: async ({ params: { organizationId, documentId } }) => {
      const key = `${organizationId}:${documentId}`;
      const document = await documentStorage.getItem(key);

      assert(document, { status: 404 });

      const [allDefinitions, allValues] = await Promise.all([
        findMany(customPropertyDefinitionStorage, (def) => def.organizationId === organizationId),
        findMany(documentCustomPropertyValueStorage, (v) => v.documentId === documentId),
      ]);

      const customProperties = buildCustomPropertiesResponse({
        definitions: allDefinitions,
        storedValues: allValues,
        documentId,
      });

      return { customProperties };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/custom-properties/:propertyDefinitionId',
    method: 'PUT',
    handler: async ({ params: { organizationId, documentId, propertyDefinitionId }, body }) => {
      const docKey = `${organizationId}:${documentId}`;
      const document = await documentStorage.getItem(docKey);

      assert(document, { status: 404 });

      const definition = await customPropertyDefinitionStorage.getItem(propertyDefinitionId);

      assert(definition, { status: 404 });

      const valueKey = `${documentId}:${propertyDefinitionId}`;
      const existing = await documentCustomPropertyValueStorage.getItem(valueKey);

      const value = get(body, ['value']);

      await documentCustomPropertyValueStorage.setItem(valueKey, {
        id: existing?.id ?? createId({ prefix: 'dcpv' }),
        documentId,
        propertyDefinitionId,
        value,
      });
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/custom-properties/:propertyDefinitionId',
    method: 'DELETE',
    handler: async ({ params: { organizationId, documentId, propertyDefinitionId } }) => {
      const docKey = `${organizationId}:${documentId}`;
      const document = await documentStorage.getItem(docKey);

      assert(document, { status: 404 });

      const valueKey = `${documentId}:${propertyDefinitionId}`;

      await documentCustomPropertyValueStorage.removeItem(valueKey);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/document-views',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const documentViews = await findMany(
        documentViewStorage,
        (view) => view.organizationId === organizationId,
      );

      return {
        documentViews: documentViews.toSorted(
          (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
        ),
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/document-views',
    method: 'POST',
    handler: async ({ params: { organizationId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const name = get(body, ['name']) as string;
      const query = get(body, ['query']) as string;
      const description = (get(body, ['description']) ?? null) as string | null;

      const existingViewsWithSameName = await findMany(
        documentViewStorage,
        (view) =>
          view.organizationId === organizationId && view.name.toLowerCase() === name.toLowerCase(),
      );

      if (existingViewsWithSameName.length > 0) {
        throw Object.assign(new FetchError('A view with this name already exists'), {
          status: 400,
          data: { error: { code: 'document_views.already_exists' } },
        });
      }

      const documentView = {
        id: createId({ prefix: 'dv' }),
        organizationId,
        name,
        query,
        description,
        createdAt: new Date(),
        updatedAt: new Date(),
      };

      await documentViewStorage.setItem(documentView.id, documentView);

      return { documentView };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/document-views/:documentViewId',
    method: 'PUT',
    handler: async ({ params: { organizationId, documentViewId }, body }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const documentView = await documentViewStorage.getItem(documentViewId);

      assert(documentView && documentView.organizationId === organizationId, {
        status: 404,
        message: 'Document view not found',
      });

      const newName = get(body, ['name']) as string | undefined;

      if (newName) {
        const existingViewsWithSameName = await findMany(
          documentViewStorage,
          (view) =>
            view.organizationId === organizationId &&
            view.id !== documentViewId &&
            view.name.toLowerCase() === newName.toLowerCase(),
        );

        if (existingViewsWithSameName.length > 0) {
          throw Object.assign(new FetchError('A view with this name already exists'), {
            status: 400,
            data: { error: { code: 'document_views.already_exists' } },
          });
        }
      }

      const updatedDocumentView = Object.assign(documentView, body, { updatedAt: new Date() });

      await documentViewStorage.setItem(documentViewId, updatedDocumentView);

      return { documentView: updatedDocumentView };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/document-views/:documentViewId',
    method: 'DELETE',
    handler: async ({ params: { organizationId, documentViewId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      const documentView = await documentViewStorage.getItem(documentViewId);

      assert(documentView && documentView.organizationId === organizationId, {
        status: 404,
        message: 'Document view not found',
      });

      await documentViewStorage.removeItem(documentViewId);
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/settings',
    method: 'GET',
    handler: async ({ params: { organizationId } }) => {
      const organization = await organizationStorage.getItem(organizationId);

      assert(organization, { status: 403 });

      return {
        organizationSettings: {
          ai: {
            autoTagging: {
              isEnabled: false,
              canCreateNewTags: false,
              maxTags: 10,
            },
          },
        },
      };
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/settings',
    method: 'PATCH',
    handler: async () => {
      throw Object.assign(new FetchError('Not available in demo'), {
        status: 501,
        data: {
          error: {
            message: 'This feature is not available in demo',
            code: 'demo.not_available',
          },
        },
      });
    },
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/share-links',
    method: 'GET',
    handler: async () => ({ shareLinks: [] }),
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/share-links',
    method: 'GET',
    handler: async () => ({ shareLinks: [] }),
  }),

  ...defineHandler({
    path: '/api/organizations/:organizationId/documents/:documentId/share-links',
    method: 'POST',
    handler: async () => {
      throw Object.assign(new FetchError('Not available in demo'), {
        status: 501,
        data: {
          error: {
            message: 'Share links are not available in demo',
            code: 'demo.not_available',
          },
        },
      });
    },
  }),
};

export const router = createRouter({ routes: inMemoryApiMock, strictTrailingSlash: false });