import { describe, expect, it } from 'vitest';

import { Clip } from '@/state/clipStore';
import { SessionStore } from '@/state/sessionStore';

import { isDownloadDisabled } from './download';

describe('isDownloadDisabled', () => {
  const mockSession = {
    userId: 'user123',
    flags: {
      'remix-contest-disable-downloads': true,
    },
  } as unknown as SessionStore;

  const mockClip = {
    id: 'clip123',
    user_id: 'user123',
    download_disabled_reason: 'remix_contest',
  } as Clip;

  it('should allow owner to download their own clip even when remix contest downloads are disabled', () => {
    const result = isDownloadDisabled(mockClip, mockSession);
    expect(result).toBe(false);
  });

  it('should disable downloads for non-owners when remix contest downloads are disabled', () => {
    const nonOwnerClip = {
      ...mockClip,
      user_id: 'different_user',
    } as Clip;

    const result = isDownloadDisabled(nonOwnerClip, mockSession);
    expect(result).toBe(true);
  });

  it('should allow downloads when no download_disabled_reason exists', () => {
    const clipWithoutDisabledReason = {
      ...mockClip,
      user_id: 'different_user',
      download_disabled_reason: undefined,
    } as Clip;

    const result = isDownloadDisabled(clipWithoutDisabledReason, mockSession);
    expect(result).toBe(false);
  });

  it('should allow downloads when remix-contest-disable-downloads flag is not set', () => {
    const sessionWithoutFlag = {
      ...mockSession,
      flags: {},
    } as SessionStore;

    const nonOwnerClip = {
      ...mockClip,
      user_id: 'different_user',
    } as Clip;

    const result = isDownloadDisabled(nonOwnerClip, sessionWithoutFlag);
    expect(result).toBe(false);
  });

  it('should handle null/undefined session gracefully', () => {
    const nullSession = null as unknown as SessionStore;
    const nonOwnerClip = {
      ...mockClip,
      user_id: 'different_user',
    } as Clip;

    const result = isDownloadDisabled(nonOwnerClip, nullSession);
    // When session is null, we can't access flags, so downloads are allowed
    expect(result).toBe(false);
  });
});
