import { Injectable, inject } from '@angular/core'; import { Observable, of, map, shareReplay, catchError } from 'rxjs'; import { ApiService } from './api.service'; import { AuthService } from './auth.service'; import { ChannelWithSubscription } from '../models'; export interface ResolvedChannel { channelId: string; displayName: string; internalName: string; } @Injectable({ providedIn: 'root' }) export class ChannelCacheService { private apiService = inject(ApiService); private authService = inject(AuthService); private channelsCache$: Observable> | null = null; getAllChannels(): Observable { const userId = this.authService.getUserId(); if (!userId) { return of([]); } return this.apiService.getChannels(userId, 'owned').pipe( map(response => response.channels), catchError(() => of([])) ); } resolveChannel(channelId: string): Observable { return this.getChannelsMap().pipe( map(channelsMap => { const channel = channelsMap.get(channelId); return { channelId, displayName: channel?.display_name || channel?.internal_name || channelId, internalName: channel?.internal_name || channelId }; }) ); } resolveChannels(channelIds: string[]): Observable> { return this.getChannelsMap().pipe( map(channelsMap => { const resolved = new Map(); for (const channelId of channelIds) { const channel = channelsMap.get(channelId); resolved.set(channelId, { channelId, displayName: channel?.display_name || channel?.internal_name || channelId, internalName: channel?.internal_name || channelId }); } return resolved; }) ); } private getChannelsMap(): Observable> { const userId = this.authService.getUserId(); if (!userId) { return of(new Map()); } if (!this.channelsCache$) { this.channelsCache$ = this.apiService.getChannels(userId, 'owned').pipe( map(response => { const map = new Map(); for (const channel of response.channels) { map.set(channel.channel_id, channel); } return map; }), catchError(() => of(new Map())), shareReplay(1) ); } return this.channelsCache$; } clearCache(): void { this.channelsCache$ = null; } }