import { TestBed } from '@angular/core/testing';
import { RoleId } from '../../models/role.model';
import { Team } from '../../models/team.model';
import { AuthStore } from '../auth/auth-store';
import { TeamPermissionsService } from './team-permissions';

describe('TeamPermissionsService', () => {
  let service: TeamPermissionsService;
  let authStore: AuthStore;

  const team: Team = {
    id: 9,
    name: 'Team A',
    alias: 'a',
    balance: 0,
    players: [
      {
        id: 1,
        firstName: 'Cap',
        lastName: 'Tain',
        balance: 0,
        active: true,
        user: { id: 42, email: null, firstName: null, lastName: null },
        teamRole: { id: 3 },
      },
    ],
    settings: [{ key: 'invite_min_role', value: '4' }],
  };

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(TeamPermissionsService);
    authStore = TestBed.inject(AuthStore);
  });

  it('denies everything when nobody is logged in', () => {
    authStore.clearSession();
    expect(service.canDo(team, 'invite')).toBe(false);
  });

  it('lets a global admin bypass all checks', () => {
    authStore.setSession('t', {
      id: 99,
      email: null,
      firstName: null,
      lastName: null,
      role: { id: RoleId.Admin },
    });
    expect(service.canDo(team, 'invite')).toBe(true);
  });

  it('uses the configured team setting instead of the built-in default', () => {
    authStore.setSession('t', {
      id: 42,
      email: null,
      firstName: null,
      lastName: null,
      role: { id: RoleId.User },
    });
    // captain (3) is below the configured invite_min_role of 4
    expect(service.canDo(team, 'invite')).toBe(false);
    // but still allowed for the default-threshold action memberManage (3)
    expect(service.canDo(team, 'memberManage')).toBe(true);
  });

  it('falls back to the built-in default when no setting exists for that action', () => {
    authStore.setSession('t', {
      id: 42,
      email: null,
      firstName: null,
      lastName: null,
      role: { id: RoleId.User },
    });
    expect(service.canDo(team, 'transactionCreate')).toBe(true);
  });

  it('ignores inactive players', () => {
    authStore.setSession('t', {
      id: 42,
      email: null,
      firstName: null,
      lastName: null,
      role: { id: RoleId.User },
    });
    const inactiveTeam: Team = {
      ...team,
      players: [{ ...team.players![0], active: false }],
    };
    expect(service.canDo(inactiveTeam, 'memberManage')).toBe(false);
  });
});
