import { describe, it, expect } from 'vitest';
import { TeamDetailsViewModel } from './TeamDetailsViewModel';
import type { GetTeamDetailsOutputDTO } from '@/lib/types/generated/GetTeamDetailsOutputDTO';

const createTeamDetailsDto = (overrides: Partial<GetTeamDetailsOutputDTO> = {}): GetTeamDetailsOutputDTO => ({
  team: {
    id: 'team-1',
    name: 'Test Team',
    tag: 'TT',
    description: 'A test team',
    ownerId: 'owner-1',
    leagues: ['league-1'],
    createdAt: '2024-01-01T00:00:00Z',
    specialization: 'endurance',
    region: 'EU',
    languages: ['en'],
    ...(overrides.team ?? {}),
  },
  membership:
    'membership' in overrides
      ? (overrides.membership ?? null)
      : {
          role: 'member',
          joinedAt: '2024-01-01T00:00:00Z',
          isActive: true,
        },
  canManage: overrides.canManage ?? true,
});

describe('TeamDetailsViewModel', () => {
  it('maps team fields and membership from DTO', () => {
    const dto = createTeamDetailsDto();
    const vm = new TeamDetailsViewModel(dto, 'current-user');

    expect(vm.id).toBe('team-1');
    expect(vm.name).toBe('Test Team');
    expect(vm.tag).toBe('TT');
    expect(vm.description).toBe('A test team');
    expect(vm.ownerId).toBe('owner-1');
    expect(vm.leagues).toEqual(['league-1']);
    expect(vm.createdAt).toBe('2024-01-01T00:00:00Z');
    expect(vm.specialization).toBe('endurance');
    expect(vm.region).toBe('EU');
    expect(vm.languages).toEqual(['en']);
    expect(vm.membership).toEqual({
      role: 'member',
      joinedAt: '2024-01-01T00:00:00Z',
      isActive: true,
    });
  });

  it('derives ownership, membership and role flags', () => {
    const dto = createTeamDetailsDto({
      membership: {
        role: 'owner',
        joinedAt: '2024-01-01T00:00:00Z',
        isActive: true,
      },
    });

    const vm = new TeamDetailsViewModel(dto, 'owner-user');

    expect(vm.isOwner).toBe(true);
    expect(vm.isMember).toBe(true);
    expect(vm.userRole).toBe('owner');
  });

  it('exposes canManage flag from DTO', () => {
    const canManageDto = createTeamDetailsDto({ canManage: true });
    const cannotManageDto = createTeamDetailsDto({ canManage: false });

    const canManageVm = new TeamDetailsViewModel(canManageDto, 'user-1');
    const cannotManageVm = new TeamDetailsViewModel(cannotManageDto, 'user-1');

    expect(canManageVm.canManage).toBe(true);
    expect(cannotManageVm.canManage).toBe(false);
  });

  it('handles null membership as non-member with default role', () => {
    const dto = createTeamDetailsDto({ membership: null });

    const vm = new TeamDetailsViewModel(dto, 'user-1');

    expect(vm.isMember).toBe(false);
    expect(vm.userRole).toBe('none');
    expect(vm.isOwner).toBe(false);
  });
});
