import {
  afterLoadDocumentPayload,
  afterUnloadDocumentPayload,
  beforeHandleAwarenessPayload,
  Extension,
  onChangePayload,
  onLoadDocumentPayload,
  onStoreDocumentPayload,
} from '@hocuspocus/server';
import * as Y from 'yjs';
import { Injectable, Logger } from '@nestjs/common';
import { TiptapTransformer } from '@hocuspocus/transformer';
import type { JSONContent } from '@tiptap/core';
import {
  getPageId,
  isRenderableObject,
  jsonToText,
  tiptapExtensions,
} from '../collaboration.util';
import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { InjectKysely } from 'nestjs-kysely';
import { KyselyDB } from '@docmost/db/types/kysely.types';
import { executeTx } from '@docmost/db/utils';
import { InjectQueue } from '@nestjs/bullmq';
import { QueueJob, QueueName } from '../../integrations/queue/constants';
import { Queue } from 'bullmq';
import {
  extractMentions,
  extractUserMentions,
} from '../../common/helpers/prosemirror/utils';
import { isDeepStrictEqual } from 'node:util';
import {
  IPageHistoryJob,
  IPageMentionNotificationJob,
} from '../../integrations/queue/constants/queue.interface';
import { Page } from '@docmost/db/types/entity.types';
import { CollabHistoryService } from '../services/collab-history.service';
import { HISTORY_FAST_INTERVAL, HISTORY_FAST_THRESHOLD } from '../constants';
import { TransclusionService } from '../../core/page/transclusion/transclusion.service';
import { PageVerificationInvalidationService } from '../../core/page/verification/page-verification-invalidation.service';
import { PageVerificationInvalidation } from '../../core/page/verification/page-verification-invalidation.types';
import { isSameDocumentContent } from '../content-comparison.util';
import { EnvironmentService } from '../../integrations/environment/environment.service';

@Injectable()
export class PersistenceExtension implements Extension {
  private readonly logger = new Logger(PersistenceExtension.name);
  private contributors: Map<string, Set<string>> = new Map();
  private readonly lastChanges = new Map<
    string,
    { at: Date; context: onChangePayload['context'] }
  >();

  constructor(
    private readonly pageRepo: PageRepo,
    @InjectKysely() private readonly db: KyselyDB,
    @InjectQueue(QueueName.AI_QUEUE) private aiQueue: Queue,
    @InjectQueue(QueueName.HISTORY_QUEUE) private historyQueue: Queue,
    @InjectQueue(QueueName.NOTIFICATION_QUEUE) private notificationQueue: Queue,
    private readonly collabHistory: CollabHistoryService,
    private readonly transclusionService: TransclusionService,
    private readonly pageVerificationInvalidationService: PageVerificationInvalidationService,
    private readonly environmentService: EnvironmentService,
  ) {}

  async onLoadDocument(data: onLoadDocumentPayload) {
    const { documentName, document } = data;
    const pageId = getPageId(documentName);

    if (!document.isEmpty('default')) {
      return;
    }

    const page = await this.pageRepo.findById(pageId, {
      includeContent: true,
      includeYdoc: true,
    });

    if (!page) {
      this.logger.warn('page not found');
      return;
    }

    if (page.ydoc) {
      this.logger.debug(`ydoc loaded from db: ${pageId}`);

      const doc = new Y.Doc();
      const dbState = new Uint8Array(page.ydoc);

      Y.applyUpdate(doc, dbState);
      return doc;
    }

    // if no ydoc state in db convert json in page.content to Ydoc.
    if (page.content) {
      this.logger.debug(`converting json to ydoc: ${pageId}`);

      const ydoc = TiptapTransformer.toYdoc(
        page.content,
        'default',
        tiptapExtensions,
      );

      Y.encodeStateAsUpdate(ydoc);
      return ydoc;
    }

    this.logger.debug(`creating fresh ydoc: ${pageId}`);
    return new Y.Doc();
  }

  async afterLoadDocument(data: afterLoadDocumentPayload) {
    // The loaded state is still queued for broadcast; flush it before the first
    // connection attaches, or every client receives the whole document again.
    data.document.flush();
  }

  async onStoreDocument(data: onStoreDocumentPayload) {
    const { documentName, document, instance } = data;

    const pageId = getPageId(documentName);
    const lastChange = this.lastChanges.get(documentName);
    // A queued retry can have an older context than the document it now snapshots.
    const lastContext = lastChange?.context ?? data.lastContext;

    const ydocState = Buffer.from(Y.encodeStateAsUpdate(document));
    let tiptapJson: JSONContent;
    let editingUserIds: string[] = [];
    let page: Page = null;
    let edited = false;
    let invalidation: PageVerificationInvalidation | null = null;

    try {
      try {
        tiptapJson = TiptapTransformer.fromYdoc(document, 'default');
      } catch (err) {
        this.logger.error(
          { err, pageId },
          'Failed to convert Yjs state to Tiptap JSON',
        );
        await this.pageRepo.saveYdocState(pageId, ydocState);
        return;
      }

      let textContent = null;
      try {
        textContent = jsonToText(tiptapJson);
      } catch (err) {
        this.logger.warn('jsonToText' + err?.['message']);
      }

      editingUserIds = this.consumeContributors(documentName);
      await executeTx(this.db, async (trx) => {
        page = await this.pageRepo.findById(pageId, {
          withLock: true,
          includeContent: true,
          trx,
        });

        if (!page) {
          this.logger.error(`Page with id ${pageId} not found`);
          return;
        }

        if (isDeepStrictEqual(tiptapJson, page.content)) {
          // Edits can return to the same visible content with a newer Yjs state.
          await this.pageRepo.saveYdocState(page.id, ydocState, trx);
          page = null;
          return;
        }

        // block ids, defaults and comments are saved too, but only visible changes count as an edit
        edited = !isSameDocumentContent(page.content, tiptapJson);

        let contributorIds = undefined;
        try {
          const existingContributors = page.contributorIds || [];
          contributorIds = Array.from(
            new Set([
              ...existingContributors,
              ...editingUserIds,
              page.creatorId,
            ]),
          );
        } catch (err) {
          //this.logger.debug('Contributors error:' + err?.['message']);
        }

        await this.pageRepo.updatePage(
          {
            content: tiptapJson,
            textContent: textContent,
            ydoc: ydocState,
            ...(edited
              ? { lastUpdatedById: lastContext?.user?.id ?? null, contributorIds }
              : { updatedAt: page.updatedAt }),
          },
          pageId,
          trx,
        );

        invalidation =
          await this.pageVerificationInvalidationService.invalidateForEdit(
            {
              pageId: page.id,
              userId: lastContext?.user?.id ?? null,
              changedAt: lastChange?.at ?? null,
              isMeaningfulChange: () => edited,
              loadPreviousState: async () => page,
            },
            trx,
          );

        this.logger.debug(`Page updated: ${pageId} - SlugId: ${page.slugId}`);
      });
    } catch (err) {
      this.logger.error(`Failed to update page ${pageId}`, err);
      editingUserIds.forEach((userId) =>
        this.trackContributor(documentName, userId),
      );
      // A rejected store has no timer left. Keep the live document pending so
      // disconnect and shutdown can flush it, preserving any newer editor's save.
      if (
        instance.documents.get(documentName) === document &&
        !instance.debouncer.isDebounced(`onStoreDocument-${documentName}`)
      ) {
        void instance.storeDocumentHooks(document, data);
      }
      throw err;
    }

    if (invalidation) {
      await this.pageVerificationInvalidationService.notifyInvalidated(
        invalidation,
        lastContext?.user?.id ?? null,
        'content',
      );
    }

    if (page && edited) {
      try {
        await this.collabHistory.addContributors(pageId, editingUserIds);
      } catch (err) {
        this.logger.error(
          { err, pageId },
          'Failed to add history contributors for page',
        );
      }

      document.broadcastStateless(
        JSON.stringify({
          type: 'page.updated',
          updatedAt: new Date().toISOString(),
          lastUpdatedById: lastContext?.user?.id,
          lastUpdatedBy: lastContext?.user
            ? {
                id: lastContext.user?.id,
                name: lastContext.user?.name,
                avatarUrl: lastContext.user?.avatarUrl,
              }
            : undefined,
        }),
      );
    }

    if (page) {
      await this.syncTransclusion(pageId, page.workspaceId, tiptapJson);
    }

    if (page) {
      const mentions = extractMentions(tiptapJson);

      const userMentions = extractUserMentions(mentions);
      const oldMentions = page.content ? extractMentions(page.content) : [];
      const oldMentionedUserIds = extractUserMentions(oldMentions).map(
        (m) => m.entityId,
      );

      if (userMentions.length > 0) {
        await this.notificationQueue.add(QueueJob.PAGE_MENTION_NOTIFICATION, {
          userMentions: userMentions.map((m) => ({
            userId: m.entityId,
            mentionId: m.id,
            creatorId: m.creatorId,
          })),
          oldMentionedUserIds,
          pageId,
          spaceId: page.spaceId,
          workspaceId: page.workspaceId,
        } as IPageMentionNotificationJob);
      }

      await this.aiQueue.add(QueueJob.PAGE_CONTENT_UPDATED, {
        pageIds: [pageId],
        workspaceId: page.workspaceId,
      });

      if (edited) await this.enqueuePageHistory(page);
    }
  }

  // Drop malformed awareness before it is broadcast
  async beforeHandleAwareness({
    states,
    context,
  }: beforeHandleAwarenessPayload) {
    const user = context?.user;

    for (const [clientId, state] of states) {
      if (!isRenderableObject(state)) {
        states.delete(clientId);
        continue;
      }

      if ('user' in state && !isRenderableObject(state.user)) {
        delete state.user;
      }

      if (state.user && user) {
        state.user.id = user.id;
        state.user.avatarUrl = user.avatarUrl ?? null;
      }

      if (
        'cursor' in state &&
        state.cursor !== null &&
        !isRenderableObject(state.cursor)
      ) {
        delete state.cursor;
      }
    }
  }

  async onChange(data: onChangePayload) {
    this.lastChanges.set(data.documentName, {
      at: new Date(),
      context: data.context,
    });
    const userId = data.context?.user?.id;
    if (!userId) return;
    this.trackContributor(data.documentName, userId);
  }

  private trackContributor(documentName: string, userId: string) {
    if (!this.contributors.has(documentName)) {
      this.contributors.set(documentName, new Set());
    }

    this.contributors.get(documentName).add(userId);
  }

  async afterUnloadDocument(data: afterUnloadDocumentPayload) {
    const documentName = data.documentName;
    this.contributors.delete(documentName);
    this.lastChanges.delete(documentName);
  }

  private consumeContributors(documentName: string): string[] {
    const contributorSet = this.contributors.get(documentName);
    if (!contributorSet) return [];
    const userIds = [...contributorSet];
    this.contributors.delete(documentName);
    return userIds;
  }

  private async enqueuePageHistory(page: Page): Promise<void> {
    const pageAge = Date.now() - new Date(page.createdAt).getTime();
    const delay =
      pageAge < HISTORY_FAST_THRESHOLD
        ? HISTORY_FAST_INTERVAL
        : this.environmentService.getPageHistoryInterval();

    await this.historyQueue.add(
      QueueJob.PAGE_HISTORY,
      { pageId: page.id } as IPageHistoryJob,
      { jobId: page.id, delay },
    );
  }

  /**
   * Refresh `page_transclusions` and `page_transclusion_references` to match
   * the page's current content. Runs outside the page-write transaction and
   * isolates each call so a failure here cannot affect the page save itself.
   * The diff is idempotent — the next save converges if a round drops anything.
   */
  private async syncTransclusion(
    pageId: string,
    workspaceId: string,
    tiptapJson: unknown,
  ): Promise<void> {
    try {
      await this.transclusionService.syncPageTransclusions(
        pageId,
        workspaceId,
        tiptapJson,
      );
    } catch (err) {
      this.logger.error(
        { err, pageId },
        'Failed to sync transclusions for page',
      );
    }
    try {
      await this.transclusionService.syncPageReferences(
        pageId,
        workspaceId,
        tiptapJson,
      );
    } catch (err) {
      this.logger.error(
        { err, pageId },
        'Failed to sync transclusion references for page',
      );
    }
  }
}
