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

const STORAGE_PREFIX = 'metoyou_friends';

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

  async addFriend(ownerId: string, friend: Friend): Promise<void> {
    const friends = this.read(ownerId).filter((entry) => entry.userId !== friend.userId);

    friends.push(friend);
    this.write(ownerId, friends);
  }

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

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

    if (!rawValue) {
      return [];
    }

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

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

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

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