import { Injectable } from '@angular/core';
import { jsonStorage } from '../../../infrastructure/persistence/json-storage.service';

const STORAGE_PREFIX = 'metoyou_direct_message_queue';

@Injectable({ providedIn: 'root' })
export class OfflineQueueRepository {
  private readonly storage = jsonStorage;

  async load(ownerId: string): Promise<string[]> {
    return this.read(ownerId);
  }

  async enqueue(ownerId: string, messageId: string): Promise<void> {
    this.write(ownerId, Array.from(new Set([...this.read(ownerId), messageId])));
  }

  async remove(ownerId: string, messageId: string): Promise<void> {
    this.write(
      ownerId,
      this.read(ownerId).filter((entry) => entry !== messageId)
    );
  }

  async clear(ownerId: string): Promise<void> {
    this.write(ownerId, []);
  }

  private read(ownerId: string): string[] {
    const parsed = this.storage.read<string[]>(this.key(ownerId), []);

    return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === 'string') : [];
  }

  private write(ownerId: string, messageIds: string[]): void {
    this.storage.write(this.key(ownerId), messageIds);
  }

  private key(ownerId: string): string {
    return `${STORAGE_PREFIX}:${ownerId}`;
  }
}
