import { Injectable } from '@angular/core';
import { jsonStorage } from '../../../infrastructure/persistence/json-storage.service';
import type { Friend } from '../domain/models/direct-message.model';

const STORAGE_PREFIX = 'metoyou_friends';

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

  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 parsed = this.storage.read<Friend[]>(this.key(ownerId), []);

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

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

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