import { MediaController } from './media.controller';

describe('MediaController', () => {
  const media = {
    getMediaHealth: jest.fn(), generateMusicFromText: jest.fn(), getMyAiMusicArchive: jest.fn(),
    getAiMusicArchiveItem: jest.fn(), renameAiMusicArchiveItem: jest.fn(), deleteAiMusicArchiveItem: jest.fn(),
    shareAiMusicArchiveItem: jest.fn(), shareAiMusicArchiveItemToFeed: jest.fn(),
  };
  const hls = { rewritePlaylist: jest.fn() };
  const controller = new MediaController(media as never, hls as never);
  const user = { sub: 'user-1', username: 'artist', tokenType: 'access' as const };

  beforeEach(() => jest.clearAllMocks());

  it('sets secure HLS headers and delegates wildcard path/signature', async () => {
    const response = { type: jest.fn(), setHeader: jest.fn() };
    hls.rewritePlaylist.mockResolvedValue('#EXTM3U');
    await expect(controller.hlsPlaylist({ '0': 'uploads/master.m3u8' }, '10', 'sig', response as never)).resolves.toBe('#EXTM3U');
    expect(response.type).toHaveBeenCalledWith('application/vnd.apple.mpegurl');
    expect(response.setHeader).toHaveBeenCalledWith('Cache-Control', 'no-cache, no-store, must-revalidate');
    expect(response.setHeader).toHaveBeenCalledWith('X-Content-Type-Options', 'nosniff');
    expect(hls.rewritePlaylist).toHaveBeenCalledWith('uploads/master.m3u8', { expires: '10', signature: 'sig' });
    await controller.hlsPlaylist({}, undefined, undefined, response as never);
    expect(hls.rewritePlaylist).toHaveBeenLastCalledWith('', { expires: undefined, signature: undefined });
  });

  it('delegates health and every authenticated archive operation', async () => {
    const dto = { prompt: 'calm' };
    await controller.mediaHealth();
    await controller.generateMusicFromText(user, dto as never);
    await controller.getMyAiMusicArchive(user, { page: 2, limit: 5 } as never);
    await controller.getAiMusicArchiveItem(user, 'item');
    await controller.renameAiMusicArchiveItem(user, 'item', { title: 'New' });
    await controller.deleteAiMusicArchiveItem(user, 'item');
    await controller.shareAiMusicArchiveItem(user, 'item');
    await controller.shareAiMusicArchiveItemToFeed(user, 'item', { content: 'listen' });
    expect(media.getMediaHealth).toHaveBeenCalled();
    expect(media.generateMusicFromText).toHaveBeenCalledWith('user-1', dto);
    expect(media.getMyAiMusicArchive).toHaveBeenCalledWith('user-1', { page: 2, limit: 5 });
    expect(media.getAiMusicArchiveItem).toHaveBeenCalledWith('user-1', 'item');
    expect(media.renameAiMusicArchiveItem).toHaveBeenCalledWith('user-1', 'item', { title: 'New' });
    expect(media.deleteAiMusicArchiveItem).toHaveBeenCalledWith('user-1', 'item');
    expect(media.shareAiMusicArchiveItem).toHaveBeenCalledWith('user-1', 'item');
    expect(media.shareAiMusicArchiveItemToFeed).toHaveBeenCalledWith('user-1', 'item', { content: 'listen' });
  });
});
