import assert from 'node:assert/strict';
import test from 'node:test';

import {
  assignPlayerToTeam,
  createPlayerTeamDraft,
  deletePlayerTeam,
  normalizeAppPlayerTeams,
  uniquePlayerTeamName,
} from './playerTeams';
import type { AppPlayer, AppPlayerTeam } from '../types/appPlayers';
import { asPlayerId, asPlayerTeamId } from '../types/ids';

void test('uniquePlayerTeamName appends suffix on collision', () => {
  const teams: AppPlayerTeam[] = [
    { id: asPlayerTeamId('t1'), name: 'Alpha', color: '#ffffff' },
  ];
  assert.equal(uniquePlayerTeamName('Alpha', teams), 'Alpha (2)');
  assert.equal(uniquePlayerTeamName('Beta', teams), 'Beta');
});

void test('normalizeAppPlayerTeams drops invalid and duplicates', () => {
  const teams = normalizeAppPlayerTeams([
    { id: 't1', name: 'A', color: '#abc' },
    { id: 't1', name: 'Dup', color: '#ffffff' },
    { id: '', name: 'Bad', color: '#ffffff' },
    null,
    { id: 't2', name: 'B', color: '#112233' },
  ]);
  assert.equal(teams.length, 2);
  assert.equal(teams[0]!.id, 't1');
  assert.equal(teams[0]!.color, '#aabbcc'); // #abc → expanded
  assert.equal(teams[1]!.color, '#112233');
});

void test('createPlayerTeamDraft has no parentId field', () => {
  const team = createPlayerTeamDraft('Team', '#ff0000', []);
  assert.equal(team.name, 'Team');
  assert.ok(!('parentId' in team));
});

void test('assignPlayerToTeam and deletePlayerTeam ungroup players', () => {
  const t1 = asPlayerTeamId('t1');
  const players: AppPlayer[] = [
    {
      id: asPlayerId('p1'),
      name: 'P',
      imageRelPath: 'files/a.png',
      sha256: 'x',
      teamId: t1,
      ringColor: '#c9a227',
      imageOffset: { x: 0, y: 0 },
      imageScale: 1,
    },
  ];
  const teams: AppPlayerTeam[] = [{ id: t1, name: 'T', color: '#ffffff' }];
  const assigned = assignPlayerToTeam(players, 'p1', null, new Set([t1]));
  assert.equal(assigned[0]!.teamId, null);
  const del = deletePlayerTeam(teams, players, t1);
  assert.equal(del.teams.length, 0);
  assert.equal(del.players[0]!.teamId, null);
});
