import { Injectable } from '@angular/core';
import type { DirectMessageConversation } from '../domain/models/direct-message.model';

const STORAGE_PREFIX = 'metoyou_direct_message_conversations';

@Injectable({ providedIn: 'root' })
export class DirectMessageRepository {
  async loadConversations(ownerId: string): Promise<DirectMessageConversation[]> {
    return this.read(ownerId);
  }

  async saveConversation(ownerId: string, conversation: DirectMessageConversation): Promise<void> {
    const conversations = this.read(ownerId).filter((entry) => entry.id !== conversation.id);

    conversations.push(conversation);
    this.write(ownerId, conversations);
  }

  async getConversation(ownerId: string, conversationId: string): Promise<DirectMessageConversation | null> {
    return this.read(ownerId).find((conversation) => conversation.id === conversationId) ?? null;
  }

  async deleteConversation(ownerId: string, conversationId: string): Promise<void> {
    this.write(ownerId, this.read(ownerId).filter((conversation) => conversation.id !== conversationId));
  }

  async markRead(ownerId: string, conversationId: string): Promise<void> {
    const conversations = this.read(ownerId).map((conversation) =>
      conversation.id === conversationId ? { ...conversation, unreadCount: 0 } : conversation
    );

    this.write(ownerId, conversations);
  }

  private read(ownerId: string): DirectMessageConversation[] {
    const rawValue = localStorage.getItem(this.key(ownerId));

    if (!rawValue) {
      return [];
    }

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

      return Array.isArray(parsed) ? parsed : [];
    } catch {
      return [];
    }
  }

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

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