import { TestBed } from '@angular/core/testing';
import { PlaylistService } from './playlist.service';
import { Storage } from '@ionic/storage-angular';
import { CantiService } from './canti.service';
import { ComunitaService } from './comunita.service';
import { signal } from '@angular/core';

describe('PlaylistService', () => {
  let service: PlaylistService;
  let mockStorage: any;
  let mockCantiService: any;
  let mockComunitaService: any;

  beforeEach(async () => {
    mockStorage = jasmine.createSpyObj('Storage', ['create', 'get', 'set']);
    mockStorage.create.and.returnValue(Promise.resolve(mockStorage));
    mockStorage.get.and.callFake((key: string) => {
      if (key === 'playlists') {
        return Promise.resolve([{ id: '1', name: 'Playlist Generale', ids: ['101', '102'] }]);
      }
      if (key === 'playlists_comunita_123456') {
        return Promise.resolve([{ id: '2', name: 'Playlist Comunita 123', ids: ['103'] }]);
      }
      return Promise.resolve(null);
    });
    mockStorage.set.and.returnValue(Promise.resolve());

    mockCantiService = jasmine.createSpyObj('CantiService', ['canti']);
    mockCantiService.canti.and.returnValue([]);

    mockComunitaService = {
      comunitaCode: signal(''),
      isFilterActive: signal(false),
      comunitaScalette: signal([]),
    };

    TestBed.configureTestingModule({
      providers: [
        PlaylistService,
        { provide: Storage, useValue: mockStorage },
        { provide: CantiService, useValue: mockCantiService },
        { provide: ComunitaService, useValue: mockComunitaService }
      ]
    });

    service = TestBed.inject(PlaylistService);
    // Simulate init() completion
    await service.init();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should load general playlists when community is not active', async () => {
    mockComunitaService.isFilterActive.set(false);
    mockComunitaService.comunitaCode.set('');
    
    await service.loadPlaylistsForCurrentContext();
    
    expect(service.playlists().length).toBe(1);
    expect(service.playlists()[0].name).toBe('Playlist Generale');
  });

  it('should load community-specific playlists when community is active', async () => {
    mockComunitaService.comunitaCode.set('123456');
    mockComunitaService.isFilterActive.set(true);
    
    await service.loadPlaylistsForCurrentContext();
    
    expect(service.playlists().length).toBe(1);
    expect(service.playlists()[0].name).toBe('Playlist Comunita 123');
  });
});
