import {CHATS_LOCAL_STORAGE_KEYS} from '@modules/chats/constants';
import {Storage} from '@services/mmkvFactory';
import {sentryLogs} from '@shared/utils';

/**
 * Per-user, per-conversation persistent storage for unsent input drafts.
 *
 * Stored in MMKV under keys shaped as `${userId}:${conversationId}` so a
 * device with multiple accounts keeps each user's drafts isolated.
 */
class ConversationDraftsClass {
  private storage: Storage;
  private currentUserId: string | null = null;

  constructor() {
    this.storage = new Storage({
      id: CHATS_LOCAL_STORAGE_KEYS.ConversationDraftsStorage,
    });
  }

  public setUserId(userId: string): void {
    if (this.currentUserId !== userId) {
      this.currentUserId = userId;
    }
  }

  private getStorageKey(conversationId: string): string | null {
    if (!this.currentUserId) {
      sentryLogs.warn({
        message: 'UserId not set, skipping draft access',
        module: 'CHATS',
        component: 'ConversationDrafts.getStorageKey',
      });
      return null;
    }
    return `${this.currentUserId}:${conversationId}`;
  }

  public get(conversationId: string): string {
    const key = this.getStorageKey(conversationId);
    if (!key) {
      return '';
    }
    return this.storage.getString(key) ?? '';
  }

  public set(conversationId: string, value: string): void {
    const key = this.getStorageKey(conversationId);
    if (!key) {
      return;
    }
    if (value.length === 0) {
      this.storage.remove(key);
      return;
    }
    this.storage.set(key, value);
  }

  public clear(conversationId: string): void {
    const key = this.getStorageKey(conversationId);
    if (!key) {
      return;
    }
    this.storage.remove(key);
  }
}

export const ConversationDrafts = new ConversationDraftsClass();
