import { describe, it, expect, vi } from 'vitest';
import { UpdateTeamUseCase } from './UpdateTeamUseCase';
import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';

describe('UpdateTeamUseCase', () => {
  it('updates team successfully', async () => {
    const mockMembership = {
      role: 'owner',
    };

    const mockTeam = {
      id: 'team-1',
      update: vi.fn().mockReturnValue({}),
    };

    const mockTeamRepository = {
      findById: vi.fn().mockResolvedValue(mockTeam),
      update: vi.fn().mockResolvedValue(undefined),
    } as unknown as ITeamRepository;

    const mockMembershipRepository = {
      getMembership: vi.fn().mockResolvedValue(mockMembership),
    } as unknown as ITeamMembershipRepository;

    const useCase = new UpdateTeamUseCase(mockTeamRepository, mockMembershipRepository);

    const command = {
      teamId: 'team-1',
      updates: { name: 'New Name', tag: 'NEW' },
      updatedBy: 'user-1',
    };

    const result = await useCase.execute(command);

    expect(result.isOk()).toBe(true);
    expect(mockMembershipRepository.getMembership).toHaveBeenCalledWith('team-1', 'user-1');
    expect(mockTeamRepository.findById).toHaveBeenCalledWith('team-1');
    expect(mockTeam.update).toHaveBeenCalledWith({ name: 'New Name', tag: 'NEW' });
    expect(mockTeamRepository.update).toHaveBeenCalledWith({});
  });

  it('returns error if insufficient permissions', async () => {
    const mockMembership = {
      role: 'member',
    };

    const mockMembershipRepository = {
      getMembership: vi.fn().mockResolvedValue(mockMembership),
    } as unknown as ITeamMembershipRepository;

    const useCase = new UpdateTeamUseCase({} as unknown as ITeamRepository, mockMembershipRepository);

    const command = {
      teamId: 'team-1',
      updates: { name: 'New Name' },
      updatedBy: 'user-1',
    };

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({ code: 'INSUFFICIENT_PERMISSIONS' });
  });

  it('returns error if team not found', async () => {
    const mockMembership = {
      role: 'owner',
    };

    const mockTeamRepository = {
      findById: vi.fn().mockResolvedValue(null),
    } as unknown as ITeamRepository;

    const mockMembershipRepository = {
      getMembership: vi.fn().mockResolvedValue(mockMembership),
    } as unknown as ITeamMembershipRepository;

    const useCase = new UpdateTeamUseCase(mockTeamRepository, mockMembershipRepository);

    const command = {
      teamId: 'team-1',
      updates: { name: 'New Name' },
      updatedBy: 'user-1',
    };

    const result = await useCase.execute(command);

    expect(result.isErr()).toBe(true);
    expect(result.unwrapErr()).toEqual({ code: 'TEAM_NOT_FOUND' });
  });
});