import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';

import type { UpdateTeamCommandDTO } from '../dtos/UpdateTeamCommandDTO';

type UpdateTeamErrorCode = 'INSUFFICIENT_PERMISSIONS' | 'TEAM_NOT_FOUND';

export class UpdateTeamUseCase {
  constructor(
    private readonly teamRepository: ITeamRepository,
    private readonly membershipRepository: ITeamMembershipRepository,
  ) {}

  async execute(command: UpdateTeamCommandDTO): Promise<Result<void, ApplicationErrorCode<UpdateTeamErrorCode>>> {
    const { teamId, updates, updatedBy } = command;

    const updaterMembership = await this.membershipRepository.getMembership(teamId, updatedBy);
    if (!updaterMembership || (updaterMembership.role !== 'owner' && updaterMembership.role !== 'manager')) {
      return Result.err({ code: 'INSUFFICIENT_PERMISSIONS' });
    }

    const existing = await this.teamRepository.findById(teamId);
    if (!existing) {
      return Result.err({ code: 'TEAM_NOT_FOUND' });
    }

    const updated = existing.update({
      ...(updates.name !== undefined && { name: updates.name }),
      ...(updates.tag !== undefined && { tag: updates.tag }),
      ...(updates.description !== undefined && { description: updates.description }),
      ...(updates.leagues !== undefined && { leagues: updates.leagues }),
    });

    await this.teamRepository.update(updated);

    return Result.ok(undefined);
  }
}