module Public
  class TeamRosterMembersController < WebBaseController
    before_action :require_login!
    before_action :set_team
    before_action :require_team_owner!
    before_action :set_member, only: %i[edit update destroy]

    def create
      member = @team.roster_members.build(member_params)
      attach_photo(member)
      member.save!
      redirect_to public_team_details_path(@team), notice: "#{member.full_name} aggiunto all'organico."
    rescue ActiveRecord::RecordInvalid => e
      redirect_to public_team_details_path(@team), alert: e.record.errors.full_messages.join(", ")
    end

    def edit
      @club = @team.club
    end

    def update
      @member.assign_attributes(member_params)
      attach_photo(@member)
      @member.save!
      redirect_to public_team_details_path(@team), notice: "Scheda aggiornata."
    rescue ActiveRecord::RecordInvalid => e
      @club = @team.club
      flash.now[:alert] = e.record.errors.full_messages.join(", ")
      render :edit, status: :unprocessable_entity
    end

    def destroy
      name = @member.full_name
      @member.destroy!
      redirect_to public_team_details_path(@team), notice: "#{name} rimosso dall'organico."
    end

    private

    def set_team
      @team = current_user.manageable_teams.find(params[:team_id])
    end

    def require_team_owner!
      require_club_owner_for_team!(@team)
    end

    def set_member
      @member = @team.roster_members.find(params[:id])
    end

    def member_params
      params.require(:team_roster_member).permit(
        :category, :full_name, :role_label, :jersey_number, :bio, :position
      )
    end

    def attach_photo(member)
      file = params.dig(:team_roster_member, :photo_file)
      member.photo_file.attach(file) if file.present?
    end
  end
end
