import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Team } from '../../domain/entities/Team';
import type { TeamMembershipRepository } from '../../domain/repositories/TeamMembershipRepository';
import type { TeamRepository } from '../../domain/repositories/TeamRepository';

export type UpdateTeamInput = {
  teamId: string;
  updatedBy: string;
  updates: {
    name?: string;
    tag?: string;
    description?: string;
    leagues?: string[];
  };
};

export type UpdateTeamResult = {
  team: Team;
};

export type UpdateTeamErrorCode = 'TEAM_NOT_FOUND' | 'PERMISSION_DENIED' | 'REPOSITORY_ERROR';

export class UpdateTeamUseCase {
  constructor(private readonly teamRepository: TeamRepository,
    private readonly membershipRepository: TeamMembershipRepository) {}

  async execute(
    command: UpdateTeamInput,
  ): Promise<Result<UpdateTeamResult, ApplicationErrorCode<UpdateTeamErrorCode, { message: string }>>> {
    try {
      const { teamId, updatedBy, updates } = command;

      const updaterMembership = await this.membershipRepository.getMembership(teamId, updatedBy);
      if (!updaterMembership || (updaterMembership.role !== 'owner' && updaterMembership.role !== 'manager')) {
        return Result.err({
          code: 'PERMISSION_DENIED',
          details: {
            message: 'User does not have permission to update this team',
          },
        });
      }

      const existing = await this.teamRepository.findById(teamId);
      if (!existing) {
        return Result.err({
          code: 'TEAM_NOT_FOUND',
          details: {
            message: '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({ team: updated });
    } catch (err) {
      const error = err as { message?: string } | undefined;

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: {
          message: error?.message ?? 'Failed to update team',
        },
      });
    }
  }
}
