import { Injectable } from '@angular/core';

const STORAGE_PREFIX = 'metoyou_direct_message_queue';

@Injectable({ providedIn: 'root' })
export class OfflineQueueRepository {
  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 rawValue = localStorage.getItem(this.key(ownerId));

    if (!rawValue) {
      return [];
    }

    try {
      const parsed = JSON.parse(rawValue) as string[];

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

  private write(ownerId: string, messageIds: string[]): void {
    localStorage.setItem(this.key(ownerId), JSON.stringify(messageIds));
  }

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