import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { AuthStore } from '../auth/auth-store';
import { TeamStore } from '../team/team-store';
import { HelpAccessService } from './help-access';

describe('HelpAccessService', () => {
  it('allows an active second treasurer to open the guide', () => {
    const access = createAccess(
      { id: 7, role: { id: 2 }, helpTextsEnabled: true },
      teamWithPlayer(7, 2, true),
    );

    expect(access.canOpenGuide()).toBe(true);
    expect(access.showContextHelp()).toBe(true);
  });

  it('does not treat an inactive responsible player as responsible', () => {
    const access = createAccess(
      { id: 7, role: { id: 2 }, helpTextsEnabled: true },
      teamWithPlayer(7, 4, false),
    );

    expect(access.canOpenGuide()).toBe(false);
    expect(access.showContextHelp()).toBe(false);
  });

  it('keeps the guide available when contextual help is disabled', () => {
    const access = createAccess(
      { id: 7, role: { id: 2 }, helpTextsEnabled: false },
      teamWithPlayer(7, 3, true),
    );

    expect(access.canOpenGuide()).toBe(true);
    expect(access.showContextHelp()).toBe(false);
  });

  it('defaults contextual help to enabled for stored users without the new field', () => {
    const access = createAccess(
      { id: 7, role: { id: 2 } },
      teamWithPlayer(7, 5, true),
    );

    expect(access.showContextHelp()).toBe(true);
  });

  it('allows global administrators without a team player assignment', () => {
    const access = createAccess(
      { id: 1, role: { id: 1 }, helpTextsEnabled: true },
      { id: 5, name: 'Team', alias: 'team', balance: 0, players: [] },
    );

    expect(access.canOpenGuide()).toBe(true);
  });
});

function createAccess(user: any, team: any): any {
  TestBed.resetTestingModule();
  TestBed.configureTestingModule({
    providers: [
      HelpAccessService,
      { provide: AuthStore, useValue: { currentUser: signal(user) } },
      { provide: TeamStore, useValue: { team: signal(team) } },
    ],
  });
  return TestBed.inject(HelpAccessService);
}

function teamWithPlayer(userId: number, roleId: number, active: boolean): any {
  return {
    id: 5,
    name: 'Team',
    alias: 'team',
    balance: 0,
    players: [
      {
        id: 9,
        firstName: 'Alex',
        lastName: 'Muster',
        balance: 0,
        active,
        teamRole: { id: roleId },
        user: { id: userId },
      },
    ],
  };
}
